package icsapp

import (
	"time"

	"gitlab.com/ics_cinnamon/voiceStatistics/icsconf"
	"gitlab.com/ics_cinnamon/voiceStatistics/icserror"
	"gitlab.com/ics_cinnamon/voiceStatistics/icslog"
	"gitlab.com/ics_cinnamon/voiceStatistics/icsnet"
	"gitlab.com/ics_cinnamon/voiceStatistics/icsstat"
	"gitlab.com/ics_cinnamon/voiceStatistics/icssvc"
)

const (
	LINEEND1 = "\r\n"
	LINEEND2 = "EOM"
)

type IcsExec struct {
	service *icssvc.IcsService
	config  *icsconf.IcsConfig
	hbNet   *icsnet.IcsTCPNet
	//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()

	l.Printf(icslog.LOG_LEVEL_FATAL, -1, "11111")
	for !exe.service.GetExit() {
		for exe.service.GetStop() {
			time.Sleep(time.Millisecond)
		}

		/////////////////////////////////////////////////////////////////////
		//start statistic tcp
		cmdDone := make(chan *icserror.IcsError)
		go func() {
			cmdErr := icsstat.ListenStatMNG()
			if cmdErr != nil {
				cmdDone <- cmdErr
				return
			}
			//defer sm.Close()

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

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

	return nil
}
