const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const ipcMain=electron.ipcMain
app.commandLine.appendSwitch('disable-http-cache');





const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

let width=800;
let height=800;
let x_move_g=0;
let y_move_g=0;
let appid = '0368433925644e9b83eeff9fff26b61e';
let uid = 1000;
let roomid = 'hongmomanu';
let uids = [];

let mainEvts=[];
let changeFlagItem = {isLeaveRoom:false};
let isblock = false;

const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
  // Someone tried to run a second instance, we should focus our window.
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore()
    mainWindow.focus()
  }
})

if (isSecondInstance) {
  app.quit()
}

function getPosition() {
  const scale = electron.screen.getPrimaryDisplay().scaleFactor;
  const x = (mainWindow.getContentBounds().x + mainWindow.getContentBounds().width) * scale;
  const y = mainWindow.getContentBounds().y * scale;
  return { x, y };
}


  
function get_position(){
  //console.log("x_move,y_move",x_move_g,y_move_g);
  //console.log('electron.screen',electron.screen.getPrimaryDisplay())
  const scale = electron.screen.getPrimaryDisplay().scaleFactor;
   var x=(mainWindow.getContentBounds().x+mainWindow.getContentBounds().width) * scale -width+x_move_g;
    var y=mainWindow.getContentBounds().y * scale +y_move_g;
    return {x,y};
}

function createWindow () {

  // Create the browser window.
  global.releasekind = 'aplus';
  let zmlearnPlugin;
  mainWindow = new BrowserWindow({width: 800, height: 800, minWidth:800, frame: true, backgroundColor: '#999999',titleBarStyle:'hidden'})

  // setTimeout(function(){
  //   var pos=get_position()
  // zmlearnPlugin.moveVideoWin(pos.x,pos.y)

  // },300)
  
  //mainWindow.maximize();

  // and load the index.html of the app.
  //local 
   mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
     slashes: true
   }))

   ipcMain.removeAllListeners(['close-agora-video','showChatView','hideChatView','show-agora-video',
  'createwin','eventbridge','resize','EnterRoom','Initplugin','changeWinViewById','moveWinById','SendWhiteBoardTest',
  'SendDeviceTest', 'OnTencentRoomNum', 'SendMessage', 'SendArgsMessage',
  'ShowRemoteWindow','LeaveRoom', 'move','zoom']);

  // test
  //mainWindow.loadURL('http://192.168.8.147:3000/');
   //mainWindow.loadURL('https://x-chat-test.zmlearn.com/');

  ipcMain.on('createwin', (evt, param, url) => {
  const wins = mainWindow.getChildWindows().filter((it) => it.getTitle() === param.title);
  if (wins.length > 0) {
    wins[0].show();
    if(wins[0].getSize()[0]==0)wins[0].loadURL(url);
    //console.log('createwin',param.width,param.height);
    wins[0].setSize(param.width,param.height);
    return;
  }
  const newWin = new BrowserWindow(Object.assign({ parent: mainWindow }, param));
  newWin.loadURL(url);
 
  // newWin.hide();

  const poi = getPosition();
  evt.sender.send('movewin', poi);
});

ipcMain.on('childevt', (evt) => {
  mainEvts.push(evt);
});


ipcMain.on('eventbridge', (evt, data) => {
  for(var i=0;i<mainEvts.length;i++){
    mainEvts[i].sender.send('eventbridge', data);
  }
  //evt.sender.send('eventbridge', data);
});

// ipcMain.on('initModule', (evt, width,height,appid,uid,roomid) => {
//   //console.log('isLeaveRoomisLeaveRoomisLeaveRoom')
//   isLeaveRoom = false;
//   zmlearnPlugin.InitModule(mainWindow.getNativeWindowHandle(),width,height,appid,uid,roomid);
//   const poi = getPosition();
//   evt.sender.send('movewin', poi);
// });

ipcMain.on('moveWinById', (evt, x, y, w, h, uid) => {
  //console.log('moveWinById',x, y, w, h, uid)
  zmlearnPlugin.moveVideoWin(parseInt(x),parseInt(y),parseInt(w),parseInt(h),uid);
  //zmlearnPlugin.showRemoteVideoWin(x,y,w,h,uid);
})
ipcMain.on('moveWinByHandle', (evt, x, y, w, h, hwnd) => {
  zmlearnPlugin.moveWinByHandle(x,y,w,h,hwnd);
  //zmlearnPlugin.showRemoteVideoWin(x,y,w,h,uid);
})




ipcMain.on('move',function(eve,type){
  //console.log('move size',type)
  // if(type==1){
  //   y_move_g=y_move_g-10;
  // }
  // else if(type==2){
  //   y_move_g=y_move_g+10;
  // }
  // else if(type==3){
  //   x_move_g=x_move_g-10;
  // }
  // else if(type==4){
  //   x_move_g=x_move_g+10;
  // }

  
  //zmlearnPlugin.moveVideoWin(pos.x,pos.y,uid)

})

ipcMain.on('zoom',function(eve,w,h){
  width = w;
  height = h;
  var pos=getPosition()
  //zmlearnPlugin.setVideoWinSize(w,h);
  //zmlearnPlugin.moveVideoWin(pos.x,pos.y,uid)
})

  ipcMain.on('ChangeFlag', function (eve,name,val) {
    console.log('ChangeFlag',name,val)
    changeFlagItem[name] = val;
    //isLeaveRoom = false;
    //if(uids.indexOf(uid)<0)uids.push(uid);
    //zmlearnPlugin.EnterRoom(JSON.stringify(jsonitem))
  })

  ipcMain.on('SendMoveWin',(evt)=>{
    const poi = getPosition();
    for(var i=0;i<mainEvts.length;i++){
      mainEvts[i].sender.send('movewin', poi);
    }
  })
  //OnTencentRoomNum
  ipcMain.on('OnTencentRoomNum', function(evt, roomId, signCode) {
    console.log('OnTencentRoomNum', roomId)
    zmlearnPlugin.OnTencentRoomNum(roomId);
  })
  //OnTencentRoomCreate
  ipcMain.on('OnTencentRoomCreate', function(evt) {
    console.log('OnTencentRoomCreate begin mu ha ha')
    zmlearnPlugin.OnTencentRoomCreate();
  })
   //OnWebRTCMessage
  ipcMain.on('OnWebRTCMessage', function(evt,msg) {
    console.log('OnWebRTCMessage ', msg)
    zmlearnPlugin.OnWebRTCMessage(msg);
  })

    //onTurnServices
  ipcMain.on('OnTurnServices', function(evt,msg) {
    console.log('onTurnServices ', msg)
    zmlearnPlugin.onTurnServices(msg);
  })

     //onSTurnServices
  ipcMain.on('OnSturnServices', function(evt,msg) {
    console.log('OnSturnServices ', msg)
    zmlearnPlugin.onSTurnServices(msg);
  })

      //OnWebRTCUserJoinRoom
  ipcMain.on('OnWebRTCUserJoinRoom', function(evt,msg) {
    console.log('OnWebRTCUserJoinRoom ', msg)
    zmlearnPlugin.OnWebRTCUserJoinRoom(msg);
  })

   //OnTencentRoomCreate
  ipcMain.on('OnWebRtcJoin', function(evt,uid) {
    console.log('OnWebRtcJoin begin ', uid)
    zmlearnPlugin.OnWebRTCJoin(uid);
  })

    //SendMessage
  ipcMain.on('SendMessage', function(evt,name,data) {
    console.log('SendMessage', name, data)
    if(zmlearnPlugin[name])zmlearnPlugin[name](data);
  })

  //SendMessage
  ipcMain.on('SendArgsMessage', function(evt,name,...args) {
    console.log('SendArgsMessage', name, ...args)
    if(zmlearnPlugin[name])zmlearnPlugin[name](...args);
  })



  ipcMain.on('muteVoice', function(evt, flag) {
    zmlearnPlugin.MuteVoice(flag);
  })
  ipcMain.on('muteVideo', function(evt, flag) {
    zmlearnPlugin.MuteVideo(flag);
  })

  ipcMain.on('EnterOneToOneRoom', function (eve,lessonstr) {
    console.log('EnterOneToOneRoom',lessonstr);
    zmlearnPlugin.enterOneToOneRoom(lessonstr)
  })

  ipcMain.on('UploadFile', function (eve,uploadstr) {
    console.log('UploadFile',uploadstr);
    zmlearnPlugin.uploadFile(uploadstr)
  })

  ipcMain.on('SendDeviceTest', function (eve) {
    console.log('SendDeviceTest');
    zmlearnPlugin.sendDeviceTest()
  })

  ipcMain.on('SendWhiteBoardTest', function (eve) {
    console.log('SendWhiteBoardTest');
    zmlearnPlugin.writingPadTest();
  })

  ipcMain.on('SendClose', function (eve) {
    console.log('SendClose');
    zmlearnPlugin.SendClose()
  })

  

   ipcMain.on('CheckFile', function (eve,list,userName,userPsw,HostUrl) {
    
    for(var i=0;i<list.length;i++){
      
      const checkStr = JSON.stringify({MsgType: "ChcekFile",lessonId: list[i]});
      //console.log('checkStr',checkStr);
      const rep = zmlearnPlugin.checkFile(checkStr);
      //console.log('check rep', rep);
      if(rep==='1'){
        const uploadStr = JSON.stringify({MsgType: "uploadFile",lessonId: list[i],userName,userPsw,HostUrl});
        console.log('uploadStr',uploadStr);
        zmlearnPlugin.uploadFile(uploadStr);
        break;
      }
      // if(zmlearnPlugin.checkFile(list[i]+"_1")){
      //   zmlearnPlugin.uploadFile(list[i]+"_1");
      //   break;
      // }
    }
    
  })
  
  
  ipcMain.on('LeaveRoom', function (eve) {
    changeFlagItem.isLeaveRoom = true;
    zmlearnPlugin.LeaveRoom();
    mainWindow.getChildWindows().map((it) => {
      it.setPosition(-1000,-1000);
      it.setSize(0,0);
      //it.hide();
      //it.setTitle('nothing')
    });
  })

  ipcMain.on('ShowRemoteWindow', function(eve,x,y,cx,cy,uid){
    console.log('ShowRemoteWindow',parseInt(x),parseInt(y),parseInt(cx),parseInt(cy),uid);
    zmlearnPlugin.showRemoteVideoWin(parseInt(x),parseInt(y),parseInt(cx),parseInt(cy),uid);
  })

  ipcMain.on('MoveAllWindowByOffsite', function(eve,px,py){
    console.log('MoveAllWindowByOffsite',parseInt(px),parseInt(py));
    zmlearnPlugin.MoveAllWindowByOffsite(parseInt(px),parseInt(py));
  })

  ipcMain.on('Initplugin', function(evt){
    
    if(!zmlearnPlugin){
      //mainEvt = evt;
      mainEvts.push(evt);
      zmlearnPlugin = require('./zmlearn');
      zmlearnPlugin.InitModule(mainWindow.getNativeWindowHandle(),width,height,appid,uid,roomid);
      zmlearnPlugin.Interface((data)=>{
       //console.log("hello",data)
       const poi = getPosition();
       //console.log(mainEvts.length);
       for(var i=0;i<mainEvts.length;i++){
          mainEvts[i].sender.send('nativecallback', data, poi);
       }
       //evt.sender.send('nativecallback', data, poi)
       //ipc.sender.send('nativecallback', data)
      })

    }
    
  })

  ipcMain.on('close window',function(evt, flag){
    isblock = flag;
  })





  //mainWindow.webContents.openDevTools()

  


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

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
     
    zmlearnPlugin.SendClose();
    const { exec,execSync } = require('child_process')
    try{
  
      //zmlearnPlugin.SendClose();

      //execSync('taskkill /F /IM ZmClient.exe')
      execSync('taskkill /F /IM DeviceTest.exe')
 
 

    }catch(e){

    }
    //app.quit();
    
    mainWindow = null;
    


  })

  mainWindow.on('close',function(e){

 


    try{
      //execSync('taskkill /F /IM  掌门1对1客户端.exe & taskkill /F /IM ZmClient.exe')
      //zmlearnPlugin.SendClose();
      if(!isblock)return;
      e.preventDefault();
      for(var i=0;i<mainEvts.length;i++){
        mainEvts[i].sender.send('show close confirm');
      }
 
       

    }catch(e){

    }

  })

  mainWindow.onbeforeunload=(e)=>{
  	e.returnValue=false;
  }



  mainWindow.on('move', function () {
    //var pos=get_position()
    
    if(changeFlagItem.isLeaveRoom)return;
    console.log('move move')
    const poi = getPosition();
    for(var i=0;i<mainEvts.length;i++){
          mainEvts[i].sender.send('movewin', poi);
    }

    //if (mainEvt)mainEvt.sender.send('movewin', poi);
    //zmlearnPlugin.moveVideoWin(pos.x,pos.y,uid)

  })

   mainWindow.on('resize', function () {
    if(changeFlagItem.isLeaveRoom)return;
    const poi = getPosition();
    //console.log(' resize  resize poi',poi)
    for(var i=0;i<mainEvts.length;i++){
      mainEvts[i].sender.send('movewin', poi);
    }
    

  })
   mainWindow.on('show', function () {
    // var pos=get_position()
    // zmlearnPlugin.moveVideoWin(pos.x,pos.y,uid)
    if(changeFlagItem.isLeaveRoom)return;
    const poi = getPosition();
    for(var i=0;i<mainEvts.length;i++){
      mainEvts[i].sender.send('movewin', poi);
    }
    //if (mainEvt)mainEvt.sender.send('movewin', poi);

  })
  
  //var pos=get_position()
  //zmlearnPlugin.moveVideoWin(pos.x,pos.y,uid)


  setTimeout(()=>mainWindow.maximize(),1000);

}



// 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.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
 

  app.quit()
})

app.on('activate', function () {
  // On OS X 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 (mainWindow === null) {
    createWindow()
  }
})

// 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.
