package simapp

import (
	"fmt"
	"runtime"
	"sync"
	"time"

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

type SimExec struct {
	service *icssvc.IcsService
}

func Init() (e *SimExec) {
	e = &SimExec{}
	e.service = icssvc.GetServiceStatus()

	return e
}

func (exe SimExec) Execute() *icserror.IcsError {
	l := icslog.GetIcsLog()
	simconf := icsconf.GetSimConfig()
	loop := simconf.Repeat
	l.Printf(icslog.LOG_LEVEL_INFO, -1, "go routine number %d", runtime.NumGoroutine())
	// chNum := simconf.Channels
	///////////////////////
	//create sip phone goroutine
	wg := new(sync.WaitGroup)
	for iter := 0; iter < loop; iter++ {
		l.Printf(icslog.LOG_LEVEL_DEBUG2, -1, "Create [%d]SimPhone#####################################", iter)

		//wg.Add(1)
		pF := func(id int) {
			l.Printf(icslog.LOG_LEVEL_DEBUG2, id, "Sim Phone[%d] Start#####################################", id)
			// for i := 0; i < loop; i++ {
			// 	fmt.Println(iter, loop)
			// 	l.Printf(icslog.LOG_LEVEL_INFO, id, "go routine number %d", runtime.NumGoroutine())
			// 	sp := simphone.NewSimPhone(id)
			// 	err := sp.Run()
			// 	if err != nil {
			// 		l.Printf(icslog.LOG_LEVEL_FATAL, id, "SIM Phone Failed-%s", err.GetError())
			// 		wg.Done()
			// 		return
			// 	}
			// 	l.Printf(icslog.LOG_LEVEL_INFO, id, "[%dth] DONE[%d]#####################################", i, loop)
			// 	l.Printf(icslog.LOG_LEVEL_INFO, id, "go routine number %d", runtime.NumGoroutine())
			// }
			fmt.Println(iter, loop)
			l.Printf(icslog.LOG_LEVEL_INFO, id, "go routine number %d", runtime.NumGoroutine())
			sp := simphone.NewSimPhone(id)
			err := sp.Run()
			if err != nil {
				l.Printf(icslog.LOG_LEVEL_FATAL, id, "SIM Phone Failed-%s", err.GetError())
				wg.Done()
				return
			}
			l.Printf(icslog.LOG_LEVEL_INFO, id, "[%dth] DONE[%d]#####################################", loop)
			l.Printf(icslog.LOG_LEVEL_INFO, id, "go routine number %d", runtime.NumGoroutine())

			l.Printf(icslog.LOG_LEVEL_DEBUG2, id, "Sim Phone[%d] Completed#####################################", id)
			wg.Done()
		}
		//}(iter)
		wg.Add(1)
		go pF(iter)
		time.Sleep(time.Millisecond)
	}
	wg.Wait()

	l.Printf(icslog.LOG_LEVEL_INFO, -1, "go routine number %d", runtime.NumGoroutine())

	l.Print(icslog.LOG_LEVEL_INFO, -1, "Bye VoiceCapture~")

	return nil
}
