const fs = require('fs') ;
const path = require('path');
const electron = require('electron');
const {ipcMain} = require('electron');
const {BrowserWindow} = electron;
const {dialog} = require('electron');
const uuid = require('./uuid');
const needle = require('needle');
const utils = require('./utils.js');
const Service = require('./service.js');

/*******************************************************************
IPC相关事件处理代码
********************************************************************/

ipcMain.on('toggleDevTool', function(event) {
  winMain.webContents.toggleDevTools();
});

ipcMain.on('getUuid', function(event) {
  event.returnValue = uuid.v1().replace(/-/g,'');
});

ipcMain.on('getAppRootDir', function(event) {
  event.returnValue = global.rootDir;
});

ipcMain.on('getConfig', function(event) {
  event.returnValue = global.clientConfig;
});

ipcMain.on('getCurServer', function(event) {
  event.returnValue = global.curServer;
});

ipcMain.on('setCurServer', function(event, serverId) {
  for(var i=0;i<global.clientConfig.servers.length;i++) {
    var server = global.clientConfig.servers[i];
    if(server.id==serverId) global.curServer = server;
  }
});

ipcMain.on('setServers', function(event, servers) {
  let curServerId;
  //if(global.curServer) curServerId = global.curServer.id;
  global.curServer = null;
  global.clientConfig.servers = servers;
  let exeFileDir = path.join(global.rootDir, "../../");
  utils.saveJSONToFile(global.clientConfig, exeFileDir+'config.json');
  for(var i=0;i<global.clientConfig.servers.length;i++) {
    var server = global.clientConfig.servers[i];
    if(!curServerId && i==0) {
      global.curServer = server;
    } /*else if(server.id==curServerId) {
      global.curServer = server;
    }*/
  }
});

ipcMain.on('requestService', function(event, servicePath, args) {
  setAuthArgs(args);
  var service = new Service();
  service.request(servicePath, args, function(req, res) {
    try {
      event.reply('onServiceResponse_'+args._requestId, req, res);
    } catch(err) {
      logger.log(err);
    }
  });
});

function formatUrl(url) {
  if(!url) return "";
  if(url.indexOf("/")!=0) url = "/"+url;
  if(url.indexOf("?")<0) {
    url += "?";
  } else {
    url += "&";
  }
  url += "_auth_org=" + global.curServer.orgcode;
  let ts = (new Date()).getTime();
  url += "&_auth_ts=" + ts;

  var signData = [global.curServer.orgcode, global.curServer.orgkey, ts];
  var iv = utils.md5(JSON.stringify(signData)).substr(0, 16);
  signData.push(iv);
  var key = utils.md5(JSON.stringify(signData));
  
  var loginData = ['loginname', global.curServer.loginname, 'pc'];
  signData.push(utils.md5(global.curServer.password));
  loginData.push(utils.md5(JSON.stringify(signData)));
  signData = null;      
  
  url += "&_auth_data="+encodeURIComponent(utils.encryptAES(JSON.stringify(loginData), key, iv));
  if(global.curServer.useHttps) {
    return "https://"+global.curServer.address+url;
  } else {
    return "http://"+global.curServer.address+":"+global.curServer.port+url;
  }
}

ipcMain.on('formatUrl', function(event, url) {
  event.returnValue = formatUrl(url);
});

function getAuthInfo() {
  let pwd = utils.md5(global.curServer.password);
  let ret = {
    loginname: global.curServer.loginname,
    pwd: pwd,
    ts: (new Date()).getTime()
  };
  var ivData = [];
  ivData = [global.curServer.loginname, pwd, "web", ret.ts];
  var iv = utils.md5(JSON.stringify(ivData)).substr(0, 16);
  ivData.push(iv);
  var key = utils.md5(JSON.stringify(ivData));
  ivData = [];
  ivData.push(global.curServer.orgcode);
  ivData.push("");
  ivData.push(global.curServer.orgkey);
  ret.data = utils.encryptAES(JSON.stringify(ivData), key, iv);
  ivData = null;
  return ret;
}

ipcMain.on('getAuthInfo', function(event) {
  event.returnValue = getAuthInfo();
});

function setAuthArgs(args) {
  args._auth_org = global.curServer.orgcode;
  args._auth_ts = (new Date()).getTime();

  var signData = [global.curServer.orgcode, global.curServer.orgkey, args._auth_ts];
  var iv = utils.md5(JSON.stringify(signData)).substr(0, 16);
  signData.push(iv);
  var key = utils.md5(JSON.stringify(signData));
  
  var loginData = ['loginname', global.curServer.loginname, 'pc'];
  signData.push(utils.md5(global.curServer.password));
  loginData.push(utils.md5(JSON.stringify(signData)));
  signData = null;     
  if(args.encArgs) loginData.push(JSON.stringify(args.encArgs));
  delete args.encArgs;      
  
  args._auth_data = utils.encryptAES(JSON.stringify(loginData), key, iv);
}

/**
 * 显示目录选择框
 */
ipcMain.on('showDirPicker', function(event, args) {
  dialog.showOpenDialog({
    title:'选择项目路径', properties: ['openDirectory']
  }).then(result => {
    if(result.canceled || result.filePaths.length==0) return;
    try {
      event.reply('onNativeDialogOK', result.filePaths[0]);
    } catch(e) {
      global.logger.logError(e);
    }
  }).catch(err => {
    global.logger.logError(err);
  });
});

/**
 * 显示文件选择对话框
 */
ipcMain.on('showFilePicker', function(event, args) {
  var options = {};
  options.properties = ['openFile'];
  if(args) {
    if(args.multiSelections) options.properties.push('multiSelections');
    if(args.createDirectory) options.properties.push('createDirectory');
    if(args.showHiddenFiles) options.properties.push('showHiddenFiles');
    if(args.title) options.title = args.title;
    if(args.defaultPath) options.defaultPath = args.defaultPath;
    if(args.filters) options.filters = args.filters;
  }
  dialog.showOpenDialog(options).then(result => {
    if(result.canceled) return;
    if(!result.filePaths || result.filePaths.length==0) return;
    var files = [];
    for(var i=0;i<result.filePaths.length;i++) {
      var file = {};
      file.code = uuid.v1().replace(/-/g,'');
      file.path = result.filePaths[i];
      file.name = path.basename(file.path);
      var stats = fs.statSync(file.path);
      file.size = stats.size;
      files.push(file);
    }
    try {
      event.reply('onNativeDialogOK', files);
    } catch(e) {
      global.logger.logError(e);
    }
  }).catch(err => {
    global.logger.logError(err);
  });
});

/**
 * 显示文件保存对话框
 */
ipcMain.on('showSaveDialog', function(event, args) {
  var options = {};
  options.title = '另存为';
  if(args) {
    if(args.title) options.title = args.title;
    if(args.defaultPath) options.defaultPath = args.defaultPath;
    if(args.filters) options.filters = args.filters;
  }
  dialog.showSaveDialog(options).then(function(ret) {
    if(ret.canceled) return;
    try {
      event.reply('onNativeDialogOK', ret.filePath);
    } catch(e) {
      global.logger.logError(e);
    }
  }).catch(err => {
    global.logger.logError(err);
  });
});

ipcMain.on('uploadFile', function(event, filePath, args, cbIndex) {
  var sender = event.sender;
  let fileName = path.basename(filePath);
  var buffer = fs.readFileSync(filePath);
  var params = {
    file : {
    buffer       : buffer,
    filename     : encodeURIComponent(fileName),
    content_type : 'multipart/form-data'
  }};
  let url = "/Upload";
  if(args) url += "?"+args;
  url = formatUrl(url);
  needle.post(url, params, {multipart: true}, function(err, resp, body) {
    if(err) {
      logger.log(err);
      logger.log(err.stack);
      if(sender) {
        try {
          sender.send('onUploadFile', cbIndex, err);
        } catch(e) {}
      }
    } else {
      logger.log(body);
      if(sender) {
        try {
          sender.send('onUploadFile', cbIndex, null, body);
        } catch(e) {}
      }
    }
  });
});

ipcMain.on('downloadFile', function(event, args, filePath, cbIndex) {
  var sender = event.sender;
  let url = "/Download";
  if(args) url += "?"+args;
  url = formatUrl(url);
  needle.get(url, { output: filePath, follow: 3 }, function(err, resp, data){
    if(err) {
      logger.log(err);
      if(sender) {
        try {
          sender.send('onDownloadFile', cbIndex, err);
        } catch(e) {}
      }
    } else {
      //logger.log(resp);
      if(sender) {
        try {
          sender.send('onDownloadFile', cbIndex, null);
        } catch(e) {}
      }
    }
  });
});

/**
 * 显示预览窗口
 */
ipcMain.on('showPreviewWindow', function(event, clientType, url) {
  var electronScreen = electron.screen;
  var size = electronScreen.getPrimaryDisplay().workAreaSize;
  var option = {
    width: size.width,
    height: size.height,
    resizable: true,
    frame: true,
    autoHideMenuBar:true,
    webPreferences: {
      nodeIntegration: false,
      nodeIntegrationInWorker: false,
      nodeIntegrationInSubFrames: false,
      sandbox: true,
      enableRemoteModule: false,
      nativeWindowOpen: true,
      v8CacheOptions: "none"
    }
  };

  let win = new BrowserWindow(option);
  //win.setAutoHideMenuBar(false);
  //win.setMenuBarVisibility(true);
  const contents = win.webContents;
  contents.on('did-finish-load', function() {
    let authInfo = getAuthInfo();
    try {
      contents.executeJavaScript("sessionStorage.setItem('l', '"+authInfo.loginname+"')");
      contents.executeJavaScript("sessionStorage.setItem('p', '"+authInfo.pwd+"')");
      contents.executeJavaScript("sessionStorage.setItem('d', '"+authInfo.data+"')");
      contents.executeJavaScript("sessionStorage.setItem('t', '"+authInfo.ts+"')");
      contents.executeJavaScript("taskMsgAuthObj.loadAuthData()");
      contents.executeJavaScript("openTFP()");
    } catch(e) {
      logger.log(e);
    }
  });
  let previewUrl;
  if(clientType=="pc") {
    previewUrl = formatUrl("/dev/pc/console.html");
  } else {
    previewUrl = formatUrl("/dev/mobile/simulator.html");
  }
  previewUrl += "&url="+url;
  win.loadURL(previewUrl);
  win.maximize();
  contents.openDevTools();
});