const path = require('path');
const fs = require('fs');
const { exec, execSync } = require('child_process');
let microSipBatePath = path.join(__dirname, 'MicroSIP');
const electron = require('electron');
const app = (electron.remote || electron).app;
if (app.isPackaged) {
  microSipBatePath = path.join(process.resourcesPath, 'MicroSIP');
}
let iniPath = path.join(microSipBatePath, 'microsip.ini');
// /exit  退出
// /minimized   最小化方式启动
// /hidden  隐藏方式启动
// /answer     回拨接起
// /hangupall   挂断
let microSip = path.join(microSipBatePath, 'microsip.exe');
let sipStatusCallBack = null;
let isCalling = false;
// 注册
function register(data) {
  // 服务器地址，端口号，用户名，密码，状态回调，日志，microsip文件夹路径
  const { registerIp, signallingPort, sipLocalNumber, sipLocalPassword, sipStateCall, KtLog = console.log, SipBatePath } = data;
  if (SipBatePath) {
    microSipBatePath = SipBatePath;
    iniPath = path.join(microSipBatePath, 'microsip.ini');
    microSip = path.join(microSipBatePath, 'microsip.exe');
  }
  try {
    execSync(`${microSip} /exit`);
    execSync(`taskkill /IM microsip.exe /F`);
  } catch (error) {}
  sipStatusCallBack = sipStateCall;
  let iniMessage = `
[Settings]
accountId=1
singleMode=1
ringingSound=
volumeRing=100
audioRingDevice=""
audioOutputDevice=""
audioInputDevice=""
micAmplification=0
swLevelAdjustment=0
audioCodecs=PCMA/8000/1 PCMU/8000/1
VAD=0
EC=1
forceCodec=0
opusStereo=0
disableMessaging=0
disableVideo=0
videoCaptureDevice=""
videoCodec=
videoH264=1
videoH263=1
videoVP8=1
videoVP9=1
videoBitrate=256
rport=1
sourcePort=0
rtpPortMin=0
rtpPortMax=0
dnsSrvNs=
dnsSrv=0
STUN=
enableSTUN=0
recordingPath=Recordings
recordingFormat=mp3
autoRecording=0
recordingButton=1
DTMFMethod=0
autoAnswer=all
autoAnswerDelay=0
autoAnswerNumber=
forwarding=
forwardingNumber=
forwardingDelay=0
denyIncoming=button
usersDirectory=
defaultAction=
enableMediaButtons=0
headsetSupport=0
localDTMF=1
enableLog=0
bringToFrontOnIncoming=1
enableLocalAccount=0
randomAnswerBox=0
crashReport=1
callWaiting=1
updatesInterval=never
checkUpdatesTime=1756461750
noResize=0
userAgent=
autoHangUpTime=0
maxConcurrentCalls=0
noIgnoreCall=0
cmdOutgoingCall=
cmdIncomingCall=
cmdCallRing=
cmdCallAnswer=
cmdCallAnswerVideo=
cmdCallBusy=
cmdCallStart=
cmdCallEnd=
minimized=0
silent=0
portKnockerHost=
portKnockerPorts=
mainX=2266
mainY=252
mainW=259
mainH=465
messagesX=727
messagesY=318
messagesW=0
messagesH=0
ringinX=0
ringinY=0
callsWidth0=0
callsWidth1=0
callsWidth2=0
callsWidth3=0
callsWidth4=0
callsWidth5=0
contactsWidth0=0
contactsWidth1=0
contactsWidth2=0
volumeOutput=100
volumeInput=100
activeTab=0
AA=0
AC=0
DND=0
alwaysOnTop=0
enableShortcuts=0
shortcutsBottom=0
lastCallNumber=/reset
lastCallHasVideo=0
callsLastKey=3
[Account1]
label=${sipLocalNumber}
server=${registerIp}:${signallingPort}
proxy=${registerIp}:${signallingPort}
domain=${registerIp}:${signallingPort}
username=${sipLocalNumber}
password=${sipLocalPassword}
authID=${sipLocalNumber}
displayName=
dialingPrefix=
dialPlan=
hideCID=0
voicemailNumber=
transport=udp
publicAddr=
SRTP=
registerRefresh=300
keepAlive=15
publish=0
ICE=0
allowRewrite=0
disableSessionTimer=0
`;
  fs.writeFileSync(iniPath, iniMessage);
  exec(`${microSip} /hidden`, function (error, stdout, stderr) {
    if (error) {
      KtLog(`启动microSip失败: ${error}`);
      return;
    }
    if (stderr) {
      KtLog(`启动microSip失败: ${stderr}`);
      return;
    }
    sipStatusCallBack('registered');
  });
  //   exec(`${microSip}`);
}
// 拨打
function sipCall(removeNumber) {
  exec(`${microSip} ${removeNumber}`, function (error, stdout, stderr) {
    if (error) {
      KtLog(`拨打microSip失败: ${error}`);
      return;
    }
    if (stderr) {
      KtLog(`拨打microSip失败: ${stderr}`);
      return;
    }
    isCalling = true;
  });
  return { code: true };
}
// 挂断
function disconnectSip() {
  exec(`${microSip} /hangupall`, function (error, stdout, stderr) {
    if (error) {
      KtLog(`挂断microSip失败: ${error}`);
      return;
    }
    if (stderr) {
      KtLog(`挂断microSip失败: ${stderr}`);
      return;
    }
  });
  isCalling = false;
  sipStatusCallBack('winClose');
}

// 拨打状态
function sipIsCallingState() {
  return isCalling;
}
module.exports = {
  register,
  sipCall,
  disconnectSip,
  sipIsCallingState,
};
