package app

import (
	"os/exec"
	"pbx-api-gin/internal/app/ami/action"
	"pbx-api-gin/internal/app/stc"
	"pbx-api-gin/internal/app/stc/active"
	"pbx-api-gin/internal/app/stc/priority"
	"pbx-api-gin/internal/app/stc/socket"
	"pbx-api-gin/pkg/lfshook"
	"pbx-api-gin/pkg/utils"
	"syscall"
	"time"
)

func StartApp() {

	//init asterisk
	if !utils.CheckAsterisk() {
		lfshook.NewLogger().Infof("Check asterisk , if not running , run cmd service asterisk start !")
		cmd := exec.Command("service", "asterisk", "start")
		cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
		err := cmd.Run()
		if err != nil {
			lfshook.NewLogger().Infof("Failed to start asterisk: %v", err)
			return
		}

		time.Sleep(3 * time.Second)
	}

	//Get cab number acording to IP
	socket.SetMasterCabNum()

	utils.LoggerDebug.Printf("Get CabNumber:%s  Master:%+v", active.CabNum, active.Master)

	//init the active status
	//active.ActivedCab = ""

	//get priority
	priority.GetPriority()

	//初始化列车信息map 列车号+车厢号
	active.InitTrainInfoMap()

	// 启动带有重连机制的连接管理协程MC1
	go stc.StartStcConnection(socket.Conn, "1")

	// 启动带有重连机制的连接管理协程MC8
	go stc.StartStcConnection(socket.Conn8, "8")

	//启动连接到Master服务器,检查Master是否在线
	//if active.CabNum == "1" {
	//	go stc.StartConnectionToSipServer(socket.ConnToSlave)
	//} else {
	//	go stc.RecvFromSipServer()
	//}

	// 启动其他服务...
	// 启动 AMI
	go func() {
		action.StartAMI(func() {
			utils.LoggerDebug.Printf("AMI callback Start .")
		}, []func(event map[string]string){})
	}()

	//refresh extension status
	time.Sleep(1 * time.Second)

	utils.ExecCmdAsync("/usr/sbin/asterisk", "-rx", "reload")
}
