package main

// #cgo LDFLAGS:  -L/usr/local/lib /usr/local/lib/libavcodec.a /usr/local/lib/libavformat.a /usr/local/lib/llibavutil.a /usr/local/lib/llibswscale.a -llibswresample.a -llibavdevice -llibavfilter

import (
	"fmt"
	"os"
	"strings"

	"gitlab.com/cinnamon/voiceagent/icsapp"
	"gitlab.com/cinnamon/voiceagent/icsconf"
	"gitlab.com/cinnamon/voiceagent/icsdblog"
	"gitlab.com/cinnamon/voiceagent/icserror"
	"gitlab.com/cinnamon/voiceagent/icslog"
	"gitlab.com/cinnamon/voiceagent/icssvc"
	"gitlab.com/cinnamon/voiceagent/icsutil"
)

func main() {
	service := icssvc.NewService()

	///////////////////////////////////
	//Demonize service
	//check icssoe pid file - ICSVC_ROOT/icssoe.pid
	//if already running, terminate self.
	/*
		if icsutil.CheckPID() {
			service.ShowServiceInfo()
			fmt.Println("icssoe Already Running. Terminating...")
			os.Exit(0)
		}
	*/

	/*
		//deamonize
		pid, derr := icsutil.Deamonize()
		if derr != nil {
			service.ShowServiceInfo()
			icserror.ICSERRDeamonize.SetError(derr)
			fmt.Println("icssoe:", icserror.ICSERRDeamonize)
			os.Exit(0)
			return
		}
		fmt.Println("PID", pid)
	*/ ////////////////////////

	//get Voice Agent home dir
	isStop := false
	var homeDir string
	for _, e := range os.Environ() {
		s := strings.SplitN(e, "=", 2)
		if strings.Compare(s[0], "ICSVB_ROOT") == 0 {
			homeDir = s[1]
			//service.SetHomeDir(s[1])
			isStop = true
			break
		}
	}
	if !isStop {
		icserror.ICSERRNotFoundHome.PrintWithCaller(1)
		return
	}

	//configuration
	configFile := fmt.Sprintf("/home/icsbot/config/icsbot.xml")
	//configFile := fmt.Sprintf("%s/config/icsvc.xml", service.GetHomeDir())
	//fmt.Println("Config file:", configFile)
	conf, confErr := icsconf.OpenConfig(configFile, homeDir)
	if confErr != nil {
		confErr.PrintWithCaller(0)
		return
	}
	if confErr := service.SetIcsConfig(conf); confErr != nil {
		confErr.PrintWithCaller(0)
	}

	icsLog, lerr := icslog.NewIcsLog(
		&conf.LogConfig,
		icslog.GetLogLevelID(conf.LogConfig.Level),
		icslog.GetLogOutputID(conf.LogConfig.Output),
		conf.LogConfig.Path,
		conf.LogConfig.Disklimit,
	)
	if lerr != nil {
		lerr.PrintWithCaller(0)
	}

	service.SetIcsLog(icsLog)
	//create log watcher
	go service.LogWatcher()

	icsdblog.NewDbInfo(
		"192.168.0.30",
		"8888",
		"logInsert",
		"POST",
	)

	info := service.ShowServiceInfo()
	info += fmt.Sprintf("iComsys Voice Agent Home: %s\n", homeDir)
	fmt.Printf("iComsys Voice Agent Home: %s\n", homeDir)
	//wd, err := os.Getwd()
	logpath := conf.LogConfig.Path
	info += fmt.Sprintf("Available Disk Space [%s]: %d MB\n", logpath, icsutil.GetDiskAvailableSpace(logpath)/1024/1024)
	fmt.Printf("Available Disk Space [%s]: %d MB\n", logpath, icsutil.GetDiskAvailableSpace(logpath)/1024/1024)
	info += conf.ShowConfig()

	//check license expiration
	//fmt.Println("Remain Expiration Months:", conf.GetRemainExpire())

	app := icsapp.Init(conf)
	//fmt.Printf("Service Started - %d\n================================\n", pid)

	info = "\n" + info
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, info)
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, "Service Started")
	icsLog.Print(icslog.LOG_LEVEL_INFO, -1, "================================")

	/////////////////////////////////
	//icsutil.CloseSTDIO()
	/////////////////////////////////

	execerr := app.Execute()
	if execerr != nil {
		execerr.PrintWithCaller(1)
		os.Exit(1)
	}

	/*
		deviceName := conf.GetDeviceName()
		pcap := icspcap.New()
		//pcap.SetFilter("")
		packetSource, pcapErr := pcap.Init(deviceName)
		//packetSource, icserr := pcap.Init("wlp1s0")
		if pcapErr != nil {
			if pcapErr.Equal(icserror.ICSERRPCAPOpenLive) {
				fmt.Printf("Device Name: %s\n", deviceName)
			}
			pcapErr.Print()
			return
		}
		fmt.Println("Filter:", pcap.GetFilter())

		if err := pcap.Run(packetSource); err != nil {
			err.Print()
		}
		defer pcap.Close()
	*/

}
