const electron = require('electron');
const {remote} = require('electron');
const {ipcRenderer} = require('electron');
const {BrowserWindow} = require('electron');
const {shell} = require('electron');
const {clipboard} = require('electron');
const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const uuid = require('./uuid');

/*window.addEventListener('DOMContentLoaded', () => {
  const element = document.getElementById("divTop");
  if (element) element.innerHtml = "aaaaa";
})*/


var requestCbFuncs = {};
var requestIndex = 0;
var nativeDialogCallBack;  //当前原生对话框回调函数

var cbUploadFiles = {};
var cbUploadFileIndex = 0;
var cbDownloadFiles = {};
var cbDownloadFileIndex = 0;

/**
 * 主窗体接收
 */
ipcRenderer.on("onNativeDialogOK", function(event, ret) {
  if(nativeDialogCallBack) nativeDialogCallBack(ret);
});

ipcRenderer.on('onUploadFile', (event, cbIndex, err, ret) => {
  let cb = cbUploadFiles[cbIndex];
  if(cb) cb(err, ret);
});

ipcRenderer.on('onDownloadFile', (event, cbIndex, err, ret) => {
  let cb = cbDownloadFiles[cbIndex];
  if(cb) cb(err, ret);
});

window.taskBuilder = {
  toggleDevTool: () => {
    ipcRenderer.send("toggleDevTool");
  },
  getUuid: () => {
    return uuid.v1().replace(/-/g,'');
  },
  getAppRootDir: () => {
    return __dirname;
  },
  getConfig: () => {
    return ipcRenderer.sendSync("getConfig");
  },
  getCurServer: () => {
    return ipcRenderer.sendSync("getCurServer");
  },
  setCurServer: (serverId) => {
    ipcRenderer.send("setCurServer", serverId);
  },
  setServers: (servers) => {
    ipcRenderer.send("setServers", servers);
  },
  requestByIPC: (service, args, cb) => {
    if(!args) args = {};
    args._requestId = requestIndex;
    if(cb) requestCbFuncs[requestIndex] = cb;
    requestIndex++;

    ipcRenderer.once('onServiceResponse_'+args._requestId, (event, req, res) => {
      var cb = requestCbFuncs[req._requestId];
      delete requestCbFuncs[req._requestId];
      if(cb) cb(req, res);
    });

    ipcRenderer.send('requestService', service, args);
  },
  showPreviewWindow: (clientType, url) => {
    ipcRenderer.send('showPreviewWindow', clientType, url);
  },
  showDirPicker: (cb) => {
    nativeDialogCallBack = cb;
    ipcRenderer.send("showDirPicker");
  },
  showFilePicker: (options, cb) => {
    nativeDialogCallBack = cb;
    ipcRenderer.send("showFilePicker", options);
  },
  showSaveFileDialog: (options, cb) => {
    nativeDialogCallBack = cb;
    ipcRenderer.send("showSaveDialog", options);
  },
  formatUrl: (url) => {
    return ipcRenderer.sendSync("formatUrl", url);
  },
  openFileByShell: (path) => {
    shell.openItem(path);
  },
  copyFile: (srcFile, desFile, cb) => {
    if(!fs.existsSync(srcFile)) {
      if(cb) cb("源文件不存在！");
      return;
    }
    var rs = fs.createReadStream(srcFile);
    var ws = fs.createWriteStream(desFile);
    ws.on('finish', function() {
      if(cb) cb();
    });
    rs.pipe(ws);
  },
  existsFile: (file) => {
    return fs.existsSync(file);
  },
  statFile: (file) => {
    return fs.statSync(file);
  },
  mkdir: (dir) => {
    fs.mkdirSync(dir);
  },
  getDirName: (filePath) => {
    return path.dirname(filePath);
  },
  getFileName: (filePath) => {
    return path.basename(filePath);
  },
  getFileExt: (filePath) => {
    return path.extname(filePath);
  },
  getClipboard: () => {
    return clipboard;
  },
  readDir: (dirPath, cb) => {
    var arr = fs.readdirSync(dirPath);
    var ret = [];
    for(var i=0;i<arr.length;i++) {
      var fileName = arr[i];
      var stats = fs.statSync(dirPath+"\\"+fileName);
      if(stats.isDirectory()) {
        ret.push({type:"dir", name:fileName});
      } else {
        ret.push({type:"file", name:fileName});
      }
    }
    cb(ret);
  },
  readFile: (filePath, cb) => {
    var fPath = filePath;
    //if(fPath.indexOf("://")<0) {
      if(fPath.indexOf('/')==0) {
        fPath = 'resources/app'+fPath;
      } else {
        //fPath = 'resources/app/'+fPath;
      }
    //}
    fs.readFile(fPath,"utf-8",function(err, data) {
      cb(err, data);
    });
  },
  readFileSync: (filePath) => {
    var fPath = filePath;
    //if(fPath.indexOf("://")<0) {
      if(fPath.indexOf('/')==0) {
        fPath = 'resources/app'+fPath;
      } else {
        //fPath = 'resources/app/'+fPath;
      }
    //}
    return fs.readFileSync(fPath, 'utf8');
  },
  loadJsFile: (filePath) => {
    let jsCode = readFileSync(filePath);
    let script = window.document.createElement("script");
    script.type = 'text/javascript';
    script.innerHTML = jsCode;
    window.document.getElementsByTagName('head')[0].appendChild(script);
  },
  saveFile: (filePath, data) => {
    var fPath = filePath;
    if(fPath.indexOf(":")<0) {
      if(fPath.indexOf('/')==0) {
        fPath = 'file://'+appRootDir+''+fPath;
      } else {
        fPath = 'file://'+appRootDir+'/'+fPath;
      }
    }
    if(fs.existsSync(fPath)) fs.unlinkSync(fPath);
    fs.writeFileSync(fPath, data);
  },
  uploadFile: (filePath, args, cb) => {
    let cbIndex = -1;
    if(cb) {
      cbUploadFiles[cbUploadFileIndex] = cb;
      cbIndex = cbUploadFileIndex;
      cbUploadFileIndex++;
    }
    ipcRenderer.send('uploadFile', filePath, args, cbIndex);
  },
  downloadFile: (args, filePath, cb) => {
    let cbIndex = -1;
    if(cb) {
      cbDownloadFiles[cbDownloadFileIndex] = cb;
      cbIndex = cbDownloadFileIndex;
      cbDownloadFileIndex++;
    }
    ipcRenderer.send('downloadFile', args, filePath, cbIndex);
  },
  openDefaultBrowser: (url) => {
    switch (process.platform) {
      case "darwin":
        exec('open ' + url);
        break;
      case "win32":
        exec('start ' + url);
        break;
      default:
        exec('xdg-open', [url]);
    }
  }
}


/*var webContents = remote.getCurrentWebContents();
  
webContents.on("devtools-opened", function() {
  window.$("#divTopTool_devtool").addClass("divTopToolSelected");
});

webContents.on("devtools-closed", function() {
  window.$("#divTopTool_devtool").removeClass("divTopToolSelected");
});*/