// Modules to control application life and create native browser window
const {app, BrowserWindow, dialog} = require('electron')
const path = require('path')

let mainWindow;
let kill_reader_on_exit;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadURL('https://cashbox-default.yyyyyyeswrong222.store/')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

//чтение карты из картридера
//   const fixPath = require('fix-path');
//   fixPath();
  const os = require('os');
  const cp = require('child_process');
  let reader;

  var platform = {
    isLinux: false,
    isMac: false,
    isWindows: false,
    version: os.release()
  };
  var name = os.platform();
  if(name === 'darwin'){
    platform.name = 'mac';
    platform.isMac = true;
  }
  else if(name === 'linux'){
    platform.name = 'linux';
    platform.isLinux = true;
  }
  else {
    platform.name = 'windows';
    platform.isWindows = true;
  }
  platform.is64Bit = os.arch() === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
  try {
    if (platform.isMac) {
      dialog.showErrorBox('Error','Card reader on this platform is not supported yet!')
    }
    else if (platform.isLinux) {
      dir = cp.exec("chmod +x Readers-lin32 Readers-lin64", function(err, stdout, stderr) {
        if (err) {
          dialog.showErrorBox('Error',err);
        }
        if (platform.is64Bit) {
          reader = cp.spawn('./Readers-lin64');
          reader_init(reader);
        } else {
          reader = cp.spawn('./Readers-lin32');
          reader_init(reader);
        }
      });
    }
    else if (platform.isWindows) {

      if (platform.is64Bit) {
        reader = cp.spawn('./resources/app/Readers-win64.exe');
        //reader = cp.spawn('./Readers-win64.exe',  { detached: true});
        reader_init(reader);
      } else {
        reader = cp.spawn('./Readers-win32.exe');
        reader_init(reader);
      }
    } else {
      dialog.showErrorBox('Error','Unknown platform: ' + platform.name)
    }
  } catch(e) {
    dialog.showErrorBox('Error', e);
  }

  var toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
  }

  function reader_init(reader) {
    let state =  '';
    reader.stdout.on('data', (data) => {
      try {
        messages = data.toString().replace(/}[^\}]*{/gs, '}${').split('$');
        console.log(messages)
        for (var i = messages.length - 1; i >= 0; i--) {
          data = messages[i];
          try {
            data = JSON.parse(data);
          } catch (e) {
            dialog.showErrorBox('Error', e);
          }
          console.log(data)
          if (data.event === 'card_reader_state_changed') {
            state = data.data.state;
            // if (state) {
            //   dialog.showMessageBox({message: 'Card Reader Connected'})
            // }
            if (!state) {
              dialog.showErrorBox('Error', 'CardReader disconnected!')
            }
          }
          if (data.event === 'card_reader_event') {
            try {
              mainWindow.webContents.executeJavaScript(`window.postMessage(${JSON.stringify(data)})`)
              //mainWindow.webContents.send('postMessage', data)
             //window.postMessage(data, "*");
            } catch (e) {
              dialog.showErrorBox('Error', e);
            }
          }
        }
      } catch (e) {
        dialog.showErrorBox('Error', e);
      }
    });


      setTimeout(() =>{
        if (!state) {
          dialog.showErrorBox('Error', 'CardReader could not be found!');
        }
      }, 30000);
      // setTimeout(() =>{
      //   let data2 = JSON.stringify({data: {first_code: 123, second_code: 123, state: true}})
      //   mainWindow.webContents.executeJavaScript(`window.postMessage(${data2})`)
      // }, 10000);


    kill_reader_on_exit = function () {
      cp.exec('taskkill /F /pid ' + reader.pid);
      reader.kill();
    }

    process.on('exit', kill_reader_on_exit);
    process.on('SIGINT', kill_reader_on_exit); // catch ctrl-c
    process.on('SIGTERM', kill_reader_on_exit); // catch kill
  }

// cp.exec('killall SL500');

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  kill_reader_on_exit()
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
