// 引入需要的文件以及常量定义
const electron = require('electron');
const crypto = require('crypto');
const log = require('electron-xlog');
const fs = require('fs');
const {ipcRenderer, crashReporter, shell} = electron;

var g_data = electron.remote.getGlobal('data');
var g_storage = localConfig;
const ELKLog = require(path.join(__dirname, '../js', 'logreport.js'));
const package = require(path.join(__dirname, '../', 'package.json'));


// 教育用的key
g_data.ticKey = "pStYbp1uoC60rSuGhT364AKP4sbJ0Pax";
g_data.expire = 300;

//log.transports.console.format = '{text}';
//log.transports.file.level = 'info';
//log.transports.file.fileName = 'tclass.log';
log.transports.file.setPath(path.join((process.platform != 'darwin' ? process.env.USERPROFILE : process.env.HOME), 'TClass'), 'TClass')

crashReporter.start({
  productName: 'tic',
  companyName: 'tencent',
  submitURL: 'https://cs.api.qcloud.com/post',
  uploadToServer: true
})

var g_ids = [
  {key: "electron_test_0", value: "eJxlj0tPg0AUhff8CsK2RmeGV2viAvugWFrbtKTGzQSHi7m2MmS4osb431XUSOLZ3MX35Z6cN8u2bWeXbk9zpfRTRZJea3Dsc9thzskfrGssZE7SNcU-CC81GpB5SWA6yH3fF4z1HSygIizxx4AjKDK6kgQNyb7YFAfZtX1-8hjjIvw8fQXvO7icZuMkTsLRgnPYnW1GY3V7mSUzlUXH*TbYxxPSh41Sd*lyz7BZRziNcP58XS3YjbdaD0iFk4B0M2gLgtWDuJrpzE-rsjVhzuPhRa*S8BF*p7ksGHqC92gLpkFddYJg3OfCZV9xrHfrA0uhX-A_"},
  {key: "electron_test_1", value: "eJxlj01Pg0AURff8CsJWI-PhQDFxgRYNjYSmrU1lM0EY2lEYcHg2WON-16LGSbybtzgn7*a*W7ZtO6u75VleFO2rAg5vnXDsC9tBzukf7DpZ8hw41eU-KIZOasHzCoQeIWaMEYRMR5ZCgazkjyFqUYBuFQfRA8eG2JfPfGz7-nSOECb*1zEVuR1hEt1fxzcsdP0Aiil*hDTI2p2ss-BwQvGi6uvoyvV36wYyUqWbMJRROFTtPF*rRulsQpLGnc*CqTfcvmw3y3ym9skDOwRPceotSHxpVIJsxO80irwJJdSge6F72apRIAgzTCg6xrE*rE*XR2Bl"},
  {key: "electron_test_2", value: "eJxlj8FOg0AQhu88BeFs7LKwLZh4oC2t24rU2EbtZUNggBUKm2VbKsZ3V1EjiXOZw-dl-vnfNF3Xje3tw2UUx-WxUky9CjD0K91AxsUfFIInLFLMksk-CGfBJbAoVSB7aBJCMEJDhydQKZ7yHwNKiJWsK6agUQwPxCYpWJ-2fclGyMSTzzVUeNbDwN-N6P2srW6e-M6h9p1cbeajZeovuwLaZrV2p56gXep4j9OXMg*oR7NgnB9QKIrFZBs*z-dkj*hIuOHmtM7K3Sl1yRFHeR25i7a4HkQqfoDfahYaOzYZPnQC2fC66gWMTGJiC32Nob1rH8QeYMI_"},
  {key: "electron_test_3", value: "eJxlj0tPg0AUhff8CsJWY2aGgmLigtKHVJuIgFU2kwnc4i3PDFPSavzvVtRI4t2cxfflnNx3Tdd1I7oPL0SaNvtacXVswdCvdYMY53*wbTHjQnFTZv8gHFqUwMVWgRwgtSyLETJ2MINa4RZ-DCghVbKpuYLuVDoSu6zgw9p304QQyi5PMVYwH*B6Hnt*4MGzh2Evo6lQYtWe2a64dZFK5-GBVL0d3rGgLPcxxSLP-XwFb2vvNZKbeuM6MvB3dtEli*UyrhJnl*RPx*nCndE5m700N6NJhRX8vmYS*2piWyPag*ywqQeBEWpRZpKvM7QP7RMFKmEq"},
  {key: "electron_test_4", value: "eJxlj0tLw0AUhff5FUPWopPJSwoumhJopEGb9CHdDOnMNE4eM2FyLW3F-66migHP5i6*j3s47xZCyF4t8tuCMf2mgMK5EzaaIBvbN3*w6ySnBVDX8H9QnDppBC0OIMwAHd-3CcZjR3KhQB7kjyEawcBoRUH0QL2R2POaDm3XTx7GDgm-zliR5QDTeD1LlrOm2sT5Vl10-QSdwvH8VbLNdFHtoCkjYCmcOCf79EWqMil3NamSts6ej2lwSaLzqi1g6eJ1lGX7x7jMdJDOt7me3rnsYVQJshW-01wc3HthOKJHYXqp1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NZryrnwANx9h5w__"},
  {key: "electron_test_8", value: "eJxlj1FPgzAUhd-5FYRXjZRWlCzZA24uKixjMJNtLw2hd6PpBlhKhxr-uw41NvG83Ifvyz0575Zt284qzq7yoqi7SlH12oBjj2wHOZd-sGk4o7miRLJ-EPqGS6D5ToEcoOf7PkbIdDiDSvEd-zHgAIWSdUUVtIoGhtgyQYe270-XCHn49uuYCt8PcH6-nDzOYvEWZ*tkMdNu0icZa05VCt12PXW3-ZPQ7eFFax4dn1MS8pDNFwEWxE2XAkXlqmORKMWF6vT*brM5TcqHUCR12k4LGY7HRqXiR-idRtBN4GNiUA2y5XU1CBh5vocJOsexPqxPruJioQ__"},
  {key: "electron_test_9", value: "eJxlj01Pg0AURff8CsLamOEb3JGqCQkFbKVN3UwQXstYmI7Dm5bW*N9V1Eji3bzFOXk3903Tdd14TJbXZVUdFEeKZwGGfqMbxLj6g0KwmpZIbVn-gzAIJoGWWwQ5QtN1XYuQqcNq4Mi27MeAFiqUB04ReqThROzrPR3bvj85hJiW-3mmCtuNcH63mcUPs9fT6tJlMe6HcKMWT13g7NYcY3Wb5*cmcvPjRaHvRfx*eYqbKHPSqgVRBIkqwkANzyvedp7fvBBHQFFli9Sz4zSR7Xo*qUTWwe80m3iB69gTegTZswMfBYuYrmnZ5CuG9q59AKnfYmU_"}
];

// 判断是否为Demo客户端
function isDemoClient(){
  return g_data.mode == 'demo';
}
// 判断是否为Saas客户端
function isSaasClient(){
  return g_data.mode == "saas";
}

// 获取业务服务器域名
function getServerDomain(){
  if (g_data.test){
    return "https://cs.api.qcloud.com";
  }else{
    return "https://iclass.api.qcloud.com";
  }
}

// 发送IPC消息
function sendIpcMessage(msg, param1, param2=0, param3=0, param4=0){
  ipcRenderer.send(msg, msg, param1, param2, param3, param4);
}

// 格式化时间
function formateDateTimeWithSep(date, showDate, showSec, seperator1, seperator2, seperator3=" "){
  var month = date.getMonth()>8 ? date.getMonth()+1 : "0"+(date.getMonth()+1);
  var strDate = date.getDate()>9 ? date.getDate() : "0"+date.getDate();
  var hour = date.getHours()>9 ? date.getHours() : "0"+date.getHours();
  var min = date.getMinutes()>9 ? date.getMinutes() : "0"+date.getMinutes();
  var sec = date.getSeconds()>9 ? date.getSeconds() :  "0"+date.getSeconds();
  var timeStr = hour + seperator2 + min;
  if (showSec) timeStr = timeStr + seperator2 + sec;
  if (showDate){
    return date.getFullYear() + seperator1 + month + seperator1 + strDate + seperator3 + timeStr;
  }else{
    return timeStr;
  }
}

// 格式化时间
function formatDateTime(date, showDate=false){
  return formateDateTimeWithSep(date, showDate, !showDate, "-", ":");
}

function formatSecs(secs, hasHour=true){
  var mins = Math.floor(secs / 60);
  secs = secs % 60
  if (hasHour){
    var hours = Math.floor(mins / 60);
    mins = mins % 60;
    return (hours>9?hours:"0"+hours)+":"+(mins>9?mins:"0"+mins)+":"+(secs>9?secs:"0"+secs)
  } else{
    return (mins>9?mins:"0"+mins)+":"+(secs>9?secs:"0"+secs)
  }
}

function formatTime(date, sep=":"){
  var hour = date.getHours()>9 ? date.getHours() : "0"+date.getHours();
  var min = date.getMinutes()>9 ? date.getMinutes() : "0"+date.getMinutes();
  var sec = date.getSeconds()>9 ? date.getSeconds() :  "0"+date.getSeconds();
  return hour+sep+min+sep+sec;
}
function formatDate(date){
  var month = date.getMonth()>8 ? date.getMonth()+1 : "0"+(date.getMonth()+1);
  var strDate = date.getDate()>9 ? date.getDate() : "0"+date.getDate();

  return ""+date.getFullYear() + month + strDate + formatTime(date, "");
}

// 判断是否测试模式
function isTestMode(){
  return g_data.test;
}

// 判断是否是老师
function isTeacherRole(){
  return g_data.role == "teacher";
}

// 更新canvas尺寸
function resizeCanvas(canvas){
  // 获取浏览器中画布的显示尺寸
  var displayWidth  = canvas.clientWidth;
  var displayHeight = canvas.clientHeight;

  // 检尺寸是否相同
  if (canvas.width  != displayWidth ||
      canvas.height != displayHeight) {

    // 设置为相同的尺寸
    canvas.width  = displayWidth;
    canvas.height = displayHeight;
  }
}

// 计算旁路直播观看地址
function calcPlayAddr(subVideo){
  var bizid = 29734;
  var streamid = g_data.classId+"_"+g_data.userId+"_"+(subVideo ? "aux" : "main");
  var md5 = crypto.createHash('md5');
  var sign = md5.update(streamid).digest('hex');
  var address = "rtmp://"+bizid+".liveplay.myqcloud.com/live/"+bizid+"_"+sign;
  log.info("[TAG-BUSS] calcPlayAddr->["+streamid+"]:"+address);
  return address;
}

// 将字符串分辨率转化为TRTC分辨率
function getResolution(strResolution){
  if (strResolution == "120x120")  return 1;
  else if (strResolution == "160x160")  return 3;
  else if (strResolution == "270x270")  return 5;
  else if (strResolution == "480x480")  return 7;
  // 4:3
  else if (strResolution == "160x120")  return 50;
  else if (strResolution == "240x180")  return 52;
  else if (strResolution == "280x210")  return 54;
  else if (strResolution == "320x240")  return 56;
  else if (strResolution == "400x300")  return 58;
  else if (strResolution == "480x360")  return 60;
  else if (strResolution == "640x480")  return 62;
  else if (strResolution == "960x720")  return 64;
  // 16:9
  else if (strResolution == "160x90")   return 100;
  else if (strResolution == "256x144")  return 102;
  else if (strResolution == "320x180")  return 104;
  else if (strResolution == "480x270")  return 106;
  else if (strResolution == "640x360")  return 108;
  else if (strResolution == "960x540")  return 110;
  else if (strResolution == "1280x720") return 112;
  else if (strResolution == "1920x1080")  return 114;
  else return 110;
}

// 是否体验版本
function isDemo(){
  return (g_data.sdkAppId == 1400162216 || g_data.sdkAppId == 1400127140);
}

// 版本对比
function compareVersion(ver1, ver2){
  var verArr1 = ver1.split(".");
  var verArr2 = ver2.split(".");
  for (var i=0; i<verArr1.length&&i<verArr2.length; i++){
      if (verArr1[i] != verArr2[i]){
          return parseInt(verArr1[i]) > parseInt(verArr2[i]);
      }
  }
  return verArr1.length>verArr2.length ? true : false;
}

// 视频渲染
function renderVideoData (c, width, height, data, mirror, crop=true) {
  if (null == c) return;
  resizeCanvas(c);
  var ctx = c.getContext("2d");
  //离屏渲染
  var tempData = data.slice();
  const arr = new Uint8ClampedArray(tempData);
  let imageData = new ImageData(arr, width, height);

  var offscreenCanvas = document.createElement('canvas');
  var offscreenContext = offscreenCanvas.getContext('2d');

  offscreenCanvas.width = width;
  offscreenCanvas.height = height;
  offscreenContext.putImageData(imageData, 0, 0);

  //黑边方式
  var top = 0, left = 0;
  //log.info("[XX] renderVideoData->"+width+"x"+height+", c: "+c.width+"x"+c.height);
  if (crop){  // 裁剪模式
    if (offscreenCanvas.width / offscreenCanvas.height < c.width / c.height) { //最长边为基准缩放
      var x = c.width / offscreenCanvas.width;
      top = (offscreenCanvas.height - c.height / x) / 2;
    } else {
      var x = c.height / offscreenCanvas.height;
      left = (offscreenCanvas.width - c.width / x) / 2;
    }
    sw = c.width / x;
    sh = c.height / x;
    if (mirror) {
      ctx.translate(c.width / 2 - c.width * -1 / 2, 0);
      ctx.scale(-1, 1);
      ctx.drawImage(offscreenCanvas, left, top, sw, sh, 0, 0, c.width, c.height);
      // 坐标参考还原
      ctx.setTransform(1, 0, 0, 1, 0, 0);
    } else {
      ctx.drawImage(offscreenCanvas, left, top, sw, sh, 0, 0, c.width, c.height);
    }
  }else{  // 黑边模式
    if (offscreenCanvas.width / offscreenCanvas.height > c.width / c.height) { //最长边为基准缩放
      var x = c.width / offscreenCanvas.width;
      top = (c.height - offscreenCanvas.height * x) / 2;
    } else {
      var x = c.height / offscreenCanvas.height;
      left = (c.width - offscreenCanvas.width * x) / 2;
    }
    sw = offscreenCanvas.width * x;
    sh = offscreenCanvas.height * x;
    ctx.fillRect(0, 0, c.width, c.height);
    if (mirror) {
      ctx.translate(c.width / 2 - c.width * -1 / 2, 0);
      ctx.scale(-1, 1);
      ctx.drawImage(offscreenCanvas, 0, 0, offscreenCanvas.width, offscreenCanvas.height, left, top, sw, sh);
      // 坐标参考还原
      ctx.setTransform(1, 0, 0, 1, 0, 0);
    } else {
      ctx.drawImage(offscreenCanvas, 0, 0, offscreenCanvas.width, offscreenCanvas.height, left, top, sw, sh);
    }
  }
}

log.hooks.push((msg, transport)=>{
  if (transport !== log.transports.file) {
    return msg;
  }

  // alert(msg.date+"|"+msg.level+"|"+msg.data);
  ELKLog.setUUID(g_data.uuid);
  ELKLog.setUserId(g_data.userId);
  ELKLog.setVersion(package.version+'.'+g_data.minVer);
  ELKLog.report(ELKLog.events.log_event, {
     extra_info: msg.data
  });

  return msg;
})
