var {app,BrowserWindow,Menu,ipcMain} = require('electron'); //No I18N
var path = require('path'); //No I18N
var content,resetdock,resetmenu,menu,mainWindow,autolaunchenabled,msg,title,dnenabled,ispending,prevNotifTime,notifcount,waitTime,loadingwin,loadingid,emptybounds;
var fs = require('fs'); //No I18N
app.on("ready",()=>{ //No I18N
    var screen=require('electron').screen; //No I18N
    var x=screen.getPrimaryDisplay().workArea.width;
    var y=screen.getPrimaryDisplay().workArea.height;
    shell=require('electron').shell;//No I18N
    emptybounds={x:0,y:23,height:0,width:x};
    mainWindow=new BrowserWindow({
        width:x,
        height:y
    });
    mainWindow.on('page-title-updated',(event,title)=>{//No I18N
      event.preventDefault();
      mainWindow.setTitle('Zoho SalesIQ');//No I18N
    });
    fs.readFile( __dirname + '/url.js', (err, data) => { //No I18N
       if (err) { throw err; }
       content=data.toString();
       processFile(content);
     });
     mainWindow.on('close',()=>{ //No I18N
       mainWindow.setMenu(null);
       app.quit();
     });
     mainWindow.webContents.on('did-start-loading',()=>{//No I18N
       showLoadingPage();
     });
     mainWindow.webContents.on('did-stop-loading',()=>{//No I18N
       closeLoadingPage();
     });
     mainWindow.webContents.on('will-navigate',(event,url)=>{  //No I18N
          if(url.indexOf("logout") !== -1 && url.indexOf("zoho.com") !== -1)
          {
            mainWindow.webContents.loadURL(content + "/desktopcliententry.sas"); //No I18N
          }
          else if(isCrmPlusProduct(url))
          {
            shell.openExternal(url);
            event.preventDefault();
          }
     });
    mainWindow.webContents.on('did-navigate',(event,url)=>{  //No I18N
      if(url.indexOf("logout") !== -1 && url.indexOf("zoho.com") !== -1)
      {
        mainWindow.webContents.loadURL(content + "/desktopcliententry.sas"); //No I18N
      }
    });
    mainWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {//No I18N

       event.preventDefault();
       var pref={nodeIntegration : false};
	   var opt={height:y,width:x,webPreferences:pref};
       if(~url.indexOf("download.do"))
       {
         mainWindow.loadURL(url);
       }
       else {
         shell.openExternal(url);
       }
    });
     ispending=false;
     notifcount=0;
     prevNotifTime=(new Date()).getTime();
    resetdock=Menu.buildFromTemplate([]);
    app.dock.setMenu(resetdock);
    resetmenu=Menu.buildFromTemplate([
    {
            label:'ZohoSalesIQ', //No I18N
            submenu:[
              {
                role : 'about' //No I18N
              },
              {
                role: 'hide' //No I18N
              },
              {
                role: 'hideothers' //No I18N
              },
              {
                role: 'unhide' //No I18N
              },
              {
                type: 'separator' //No I18N
              },
              {
                label:'Clear Cache', //No I18N
                click:function()
                {
                  resetCache();
                }
              },
              {
                label:'Quit', //No I18N
                role:'quit' //No I18N
              }
            ]
      },
      {
        label: 'Edit',//No I18N
        submenu: [
          {
            role: 'undo' //No I18N
          },
          {
            role: 'redo' //No I18N
          },
          {
            type: 'separator' //No I18N
          },
          {
            role: 'cut' //No I18N
          },
          {
            role: 'copy' //No I18N
          },
          {
            role: 'paste' //No I18N
          },
          {
            role: 'pasteandmatchstyle' //No I18N
          },
          {
            role: 'delete' //No I18N
          },
          {
            role: 'selectall' //No I18N
          }
        ]
      },
      {
            label:'Page', //No I18N
            submenu:
          [
            {
                role: 'reload' //No I18N
            },
            {
                 label : 'Back',  //No I18N
                 click:function()
                {
                  if(mainWindow.webContents.canGoBack())
                  {
                    mainWindow.webContents.goBack();
                  }
                }
            },
            {
                 label : 'Go Forward',  //No I18N
                 click:function()
                {
                  if(mainWindow.webContents.canGoForward())
                  {
                    mainWindow.webContents.goForward();
                  }
                }
            },
            {
                label: 'Login to SalesIQ',//No I18N
                click:function()
               {
                  mainWindow.loadURL(content+'/desktopcliententry.sas');//No I18N
               }
            },
            {
                role: 'toggledevtools'  //No I18N
            },
            {
                type: 'separator' //No I18N
            },
            {
                role: 'resetzoom' //No I18N
            },
            {
                role: 'zoomin' //No I18N
            },
            {
                role: 'zoomout' //No I18N
            },
            {
                type: 'separator' //No I18N
            },
            {
                role: 'togglefullscreen' //No I18N
            }
          ]
      },
      {
            label:'Window', //No I18N
            submenu:
            [
              {
                  role: 'minimize' //No I18N
              },
              {
                  role: 'togglefullscreen' //No I18N
              },
              {
                  role: 'close' //No I18N
              }
            ]
      }
    ]);

    Menu.setApplicationMenu(resetmenu);

    var isOSX;
    var OS=process.platform;
    if(OS == "darwin"){ //No I18N
      isOSX=true;
    }
    else {
      isOSX=false;
    }
    menu=Menu.buildFromTemplate([
      {
            label:'ZohoSalesIQ', //No I18N
            submenu:[
              {
                role : 'about' //No I18N
              },
              {
                role: 'hide' //No I18N
              },
              {
                role: 'hideothers' //No I18N
              },
              {
                role: 'unhide' //No I18N
              },
              {
                type: 'separator' //No I18N
              },
              {
                label:'Clear Cache', //No I18N
                click:function()
                {
                  resetCache();
                }
              },
              {
                label:'Quit', //No I18N
                role:'quit' //No I18N
              }
            ]
      },
      {
        label: 'Edit', //No I18N
        submenu: [
          {
            role: 'undo' //No I18N
          },
          {
            role: 'redo' //No I18N
          },
          {
            type: 'separator' //No I18N
          },
          {
            role: 'cut' //No I18N
          },
          {
            role: 'copy' //No I18N
          },
          {
            role: 'paste' //No I18N
          },
          {
            role: 'pasteandmatchstyle' //No I18N
          },
          {
            role: 'delete' //No I18N
          },
          {
            role: 'selectall' //No I18N
          }
        ]
      },
      {
            label:'Page', //No I18N
            submenu:
          [
            {
                role: 'reload' //No I18N
            },
            {
                 label : 'Back',  //No I18N
                 click : function()
                 {
                   if(mainWindow.webContents.canGoBack())
                   {
                      mainWindow.webContents.goBack();
                   }
                 }
            },
            {
                 label : 'Go Forward',  //No I18N
                 click:function()
                {
                  if(mainWindow.webContents.canGoForward())
                  {
                    mainWindow.webContents.goForward();
                  }
                }
            },
            {
                label: 'SalesIQ Home',//No I18N
                click:function()
               {
                  mainWindow.loadURL(content+'/desktopcliententry.sas');//No I18N
               }
            },
            {
                role: 'toggledevtools'  //No I18N
            },
            {
                type: 'separator' //No I18N
            },
            {
                role: 'resetzoom' //No I18N
            },
            {
                role: 'zoomin' //No I18N
            },
            {
                role: 'zoomout' //No I18N
            },
            {
                type: 'separator' //No I18N
            },
            {
                role: 'togglefullscreen' //No I18N
            }
          ]
      },
      {
            label:'Window', //No I18N
            submenu:
            [
              {
                  role: 'minimize' //No I18N
              },
              {
                  role: 'togglefullscreen' //No I18N
              },
              {
                  role: 'close' //No I18N
              }
            ]
      },
      {
        label:'Preferences', //No I18N
        submenu:
        [
          {
            label:'Edit Profile', //No I18N
            click:function()
            {
                  mainWindow.webContents.send('pref','editprofile'); //No I18N
            }
          },
          {
              label:'Sounds', //No I18N
              click:function()
              {
                mainWindow.webContents.send('pref','sounds'); //No I18N

              }
          },
          {
            label:'Themes', //No I18N
            click:function()
            {
              mainWindow.webContents.send('pref','themes'); //No I18N
            }
          },
          {
            label: 'Notifications', //No I18N
            submenu:
            [
              {
                label:'Enable', //No I18N
                type:'radio', //No I18N
                click:function()
                {
                  if(dnenabled === false)
                  {
                    mainWindow.webContents.send('togglenotif',true);//No I18N
                    dnenabled=true;
                  }
                }

              },
              {
                label:'Disable',//No I18N
                type:'radio',//No I18N
                click:function()
                {
                  if(dnenabled === true)
                  {
                    mainWindow.webContents.send('togglenotif',false);//No I18N
                    dnenabled=false;
                  }
                }

              }
            ]
          }

        ]
      },
      {
        label:'Options', //No I18N
        submenu:
        [
          {
            label:'Internal Chat History', //No I18N
            click:function()
            {
              mainWindow.webContents.send('show','chathistory'); //No I18N
            }
          },
          {
            label:'Chat with colleague', //No I18N
            click:function()
            {
              mainWindow.webContents.send('show','mycolleagues'); //No I18N
            }
          },
          {
            label:'Message Board', //No I18N
            click:function()
            {
              mainWindow.webContents.send('show','messageboard'); //No I18N
            }
          }
        ]

  },
      {
          role: 'help', //No I18N
          submenu:
          [
            {
              label: 'User Guide', //No I18N
              click () {
                          require('electron').shell.openExternal('https://www.zoho.com/salesiq/help/') //No I18N
                        }
            },
            {
              label: 'Keyboard Shortcuts', //No I18N
              click:function()
              {
                mainWindow.webContents.send('show','shortcut'); //No I18N
              }
            },
            {
              label:'Ask for help', //No I18N
              click:function()
              {
                mainWindow.webContents.send('show','feedback'); //No I18N
              }
            }
          ]
      }
    ]);

    var notifWindow,opened="false"; //No I18N

    ipcMain.on('add-vist-notif',(event,args)=>{ //No I18N
      if(dnenabled && !mainWindow.isFocused())
      {
        if(isOSX)
        {
          try {
            setTimeout(function(){
            const notifier = require('node-notifier'); //No I18N
            var obj={};
              const noticenter = new notifier.NotificationCenter();
              title='New Visitor';//No I18N
              msg=args.visname +'  says  ' + args.question;//No I18N
              ispending=true;
            noticenter.notify({
                    title:title,
                    message: msg ,
                    actions: ['Accept'], //No I18N
                    closeLabel: 'Ignore', //No I18N
                    wait:true,
                    timeout:args.time
                  },
                  function(err, response, metadata) {
                    if (err){ throw err; }
                    if(metadata.activationValue == 'Accept') //No I18N
                    {
                      ispending=false;
                      mainWindow.restore();
                      mainWindow.focus();
                      mainWindow.webContents.send('pickup',args.visid); //No I18N
                    }
                    else if(metadata.activationValue == 'Ignore'){ //No I18N
                        ispending=false;
                        mainWindow.webContents.send('ignore',args.visid); //No I18N
                    }

                });
                noticenter.on('click', function (notifierObject, options) { //No I18N
                      ispending=false;
                      mainWindow.restore();
                      mainWindow.focus();
                 });
                 noticenter.on('timeout', function (notifierObject, options) { //No I18N
                      ispending=false;
                 });
                 notifcount++;
              },checkExceedNotifs());
          } catch (e) {

          }


      }
    }

    });
      ipcMain.on('transfer-notif',(event,arg)=>{ //No I18N
      if(dnenabled  && !mainWindow.isFocused())
      {
        try {
          setTimeout(function(){
        const notifier = require('node-notifier'); //No I18N
        const noticenter = new notifier.NotificationCenter();
        var obj={};
        ispending=true;
        title=arg;
        msg='Chat Transfer';//No I18N
        noticenter.notify({
              title:title,
              message:msg,
              actions: ['Accept'], //No I18N
              closeLabel: 'Reject', //No I18N
              wait:true,
              timeout:30
            },
            function(err, response, metadata) {
              if (err){ throw err; }
              if(metadata.activationValue == 'Accept') //No I18N
              {
                ispending=false;
                mainWindow.restore();
                mainWindow.focus();
                mainWindow.webContents.send('accept-trans-chat',obj); //No I18N
              }
              else if(metadata.activationValue == 'Reject'){ //No I18N
                  ispending=false;
                  mainWindow.webContents.send('reject-trans-chat',obj); //No I18N
              }

          });
           noticenter.on('click', function (notifierObject, options) { //No I18N
                ispending=false;
                mainWindow.restore();
                mainWindow.focus();
            });
            noticenter.on('timeout', function (notifierObject, options) { //No I18N
                ispending=false;
            });
            notifcount++;
            },checkExceedNotifs());
          }catch (e) {

          }
        }
    });
    ipcMain.on('initMenu',(event,args)=>{ //No I18N
       dnenabled=args;
       if(dnenabled == true){
         menu.items[4].submenu.items[3].submenu.items[0].checked=true;
       }
       else {
         menu.items[4].submenu.items[3].submenu.items[1].checked=true;
       }
       menu.items[0].submenu.items[5].enabled=false;
      Menu.setApplicationMenu(menu);
    });
    ipcMain.on('conn-restored',(event,args)=>{ //No I18N
      if(dnenabled  && !mainWindow.isFocused())
      {
          if(isOSX)
          {
            try{
              setTimeout(function(){
              const notifier = require('node-notifier'); //No I18N
              const noticenter = new notifier.NotificationCenter();
              noticenter.notify({
                      title:'Connected', //No I18N
                      message:'Restored SalesIQ', //No I18N
                      timeout:5
              },
              function(err, response, metadata) {});
              noticenter.on('click', function (notifierObject, options) { //No I18N
                     ispending=false;
                     if(mainWindow.isMinimized())
                     {
                          mainWindow.restore();
                     }
                     mainWindow.focus();
              });
              notifcount++;
              },checkExceedNotifs());
            } catch (e) {

            }
          }
      }
    });
    ipcMain.on('conn-lost',(event,args)=>{ //No I18N
      if(dnenabled  && !mainWindow.isFocused())
      {
          if(isOSX)
          {
            try{
              setTimeout(function(){
              const notifier = require('node-notifier'); //No I18N
              const noticenter = new notifier.NotificationCenter();
              noticenter.notify({
                      title:'Connection Lost', //No I18N
                      message:'Attempting to reconnect..', //No I18N
                    },
                    function(err, response, metadata) {});
                    noticenter.on('click', function (notifierObject, options) { //No I18N
                           ispending=false;
                           if(mainWindow.isMinimized())
                           {
                                mainWindow.restore();
                           }
                           mainWindow.focus();
                    });
                    notifcount++;
                    },checkExceedNotifs());
                  }
                  catch (e) {

                  }
          }
        }
    });
    ipcMain.on('logout',(event,arg)=>{ //No I18N
        resetmenu.items[0].submenu.items[5].enabled=true;
        Menu.setApplicationMenu(resetmenu);
        app.dock.setMenu(resetdock);
        app.dock.setBadge('');
    });
    ipcMain.on('close-notif',(event,arg)=>{ //No I18N
      if( ispending == true )
      {
        try{
        var notifier = require('node-notifier'); //No I18N
        var obj={};
        var noticenter = new notifier.NotificationCenter();
        noticenter.notify({
                    title:title,
                    message: msg,
                    wait:true,
                    timeout:1
        });

        ispending=false;
        }catch (e) {

        }
      }
    });
    ipcMain.on('custom-notif',(event,arg)=>{ //No I18N
     if(dnenabled  && !mainWindow.isFocused() && !(arg.type == "chatbar"))
     {
      try{
      setTimeout(function(){
      ispending=true;
      var notifier = require('node-notifier'); //No I18N
      var noticenter = new notifier.NotificationCenter();
      if(arg.type == 3 || arg.type == 2)
      {
         arg.title=" ";//No I18N
      }
      noticenter.notify({
                  title:arg.title,
                  message: arg.message,
                  wait:true,
                  timeout:5
      },
      function(err, response, metadata) {});
      noticenter.on('click', function (notifierObject, options) { //No I18N
            ispending=false;
            mainWindow.restore();
            mainWindow.focus();
            if(arg.type == 3 || arg.type == 2)
            {
              var sendobj={};
              sendobj.type=((arg.type==3) ? 'messageboard' :'userchat' ); //No I18N
              sendobj.wmsid=arg.wmsid;
              mainWindow.webContents.send('open',sendobj); //No I18N
            }
       });
       noticenter.on('timeout', function (notifierObject, options) { //No I18N
            ispending=false;
       });
       notifcount++;
       },checkExceedNotifs());
      }
      catch(e){}
     }
    });
});
function processFile()
{
  mainWindow.loadURL(content + "/desktopcliententry.sas"); //No I18N
}
function resetCache()
{
if(mainWindow.getURL().includes("desktopcliententry.sas") || mainWindow.getURL().includes("password"))
{
  mainWindow.webContents.session.clearCache(function(){});
  mainWindow.webContents.session.clearStorageData();
}
}

function checkExceedNotifs()
{
  waitTime=0;
  if(notifcount > 4)
  {
    currTime=(new Date()).getTime();
    if(currTime-prevNotifTime < 5000)
    {
      waitTime=5000;
    }
    notifcount=0;
  }
  if ( notifcount == 0)
  {
      prevNotifTime=(new Date()).getTime();
  }
  return waitTime;
}

function isCrmPlusProduct(url)
{
  var products=["crm.zoho.com","desk.zoho.com","campaigns.zoho.com","survey.zoho.com","projects.zoho.com","social.zoho.com","motivator.zoho.com","reports.zoho.com"];//No I18N
  for(var index in products)
  {
      if(~url.indexOf(products[index]))
      {
        return true;
      }
  }
  return false;
}

function showLoadingPage()
{
  if(!mainWindow.isFocused())
  {
    return;
  }
    loadingid=setTimeout(function(){
    var screen=require('electron').screen; //No I18N
    var x=screen.getPrimaryDisplay().workArea.width;
    var y=screen.getPrimaryDisplay().workArea.height;
    var pref={nodeIntegration:false};
      loadingwin=new BrowserWindow({
      show:false
    });
    if(mainWindow.isFocused())
    {
      try{
        loadingwin.setBounds(mainWindow.getBounds());
        loadingwin.loadURL('file://'+__dirname+'/loading.html');//No I18N
        loadingwin.show();
        mainWindow.setBounds(emptybounds);
        mainWindow.blur();
      }
      catch(e){}
    }
  },500);
}

function closeLoadingPage()
{
  try{
  clearTimeout(loadingid);
  if(loadingwin)
  {
    let bounds=loadingwin.getBounds();
    loadingwin.close();
    mainWindow.setBounds(bounds);
  }
  }catch(e){
  }
}