package icsapp

import (
	// "strings"
	"time"

	"gitlab.com/ics_cinnamon/voicegateway/icsconf"
	"gitlab.com/ics_cinnamon/voicegateway/icserror"
	"gitlab.com/ics_cinnamon/voicegateway/icslog"
	"gitlab.com/ics_cinnamon/voicegateway/icssessionmanager"
	"gitlab.com/ics_cinnamon/voicegateway/icssvc"
)

type IcsExec struct {
	service *icssvc.IcsService
	config  *icsconf.IcsConfig
	//pcap    icspcap.IcsPcap
}

func Init(conf *icsconf.IcsConfig) (e *IcsExec) {
	e = &IcsExec{}
	e.service = icssvc.GetServiceStatus()
	e.config = conf
	//e.pcap = icspcap.New()

	return e
}

func (exe IcsExec) Execute() *icserror.IcsError {
	l := icslog.GetIcsLog()

	for !exe.service.GetExit() {
		for exe.service.GetStop() {
			time.Sleep(time.Millisecond)
		}
		//init session manager and run session, listen SIP port
		sm := icssessionmanager.NewSessionManager()
		if sm == nil {
			l.Print(icslog.LOG_LEVEL_FATAL, -1, "Could not init Session Manager!!!")
			return icserror.ICSERRSVCInit
		}
		sm.Load()

		///////////////////////////////
		//start sip processor
		smDone := make(chan *icserror.IcsError)
		go func() {
			smErr := sm.Run()
			if smErr != nil {
				smDone <- smErr
				return
			}
			defer sm.Close()

			//smDone <- nil
		}()

		/////////////////////////////////////////////////////////////////////
		//start bot-command TCP listener
		// cmdDone := make(chan *icserror.IcsError)
		// bcValue := strings.ToUpper(exe.config.CommandConfig.Value)
		// if strings.Compare("TRUE", bcValue) == 0 {
		// 	go func() {
		// 		cmdErr := sm.RunBotCommandMNG()
		// 		if cmdErr != nil {
		// 			cmdDone <- cmdErr
		// 			return
		// 		}
		// 		//defer sm.Close()

		// 		//cmdDone <- nil
		// 	}()
		// }

		select {
		case err := <-smDone:
			l.Printf(icslog.LOG_LEVEL_INFO, -1, "Closed SessionManager: %s", err)
			if err != nil {
				//err.Print()
				return err
			}
		// case err := <-cmdDone:
		// 	l.Printf(icslog.LOG_LEVEL_INFO, -1, "Closed BotCommand manager: %s", err)
		// 	if err != nil {
		// 		//err.Print()
		// 		return err
		// 	}
		}

	}

	return nil
}
