package controller

/*
#include <uvdbus/smart_sound.h>
*/
import "C"
import (
	"context"
	"encoding/json"
	"fmt"
	. "netease_control_center/globals"
	"netease_control_center/interfaces"
	"netease_control_center/interfaces/cserveraddr"
	"netease_control_center/interfaces/eventPoint"
	"netease_control_center/interfaces/http"
	"netease_control_center/interfaces/log"
	"netease_control_center/interfaces/schedule"
	. "netease_control_center/interfaces/schedule"
	. "netease_control_center/interfaces/vui"
	"netease_control_center/modules/hardware/led_mcu"
	"netease_control_center/modules/hardware/mcu_leds/atservice"
	"netease_control_center/modules/hardware/misc"
	"netease_control_center/modules/player"
	"netease_control_center/modules/storage"
	"netease_control_center/modules/wifi"
	"netease_control_center/nembd/controller/adau1761"
	"netease_control_center/nembd/util"
	"netease_control_center/test"
	"netease_control_center/utils/ntp"
	"sync"
	"time"
)

var (
	bootBoardChan          chan BootStage = make(chan BootStage, 1)
	bootBoardMutex         sync.Mutex
	initCtx, initCtxCancel = context.WithCancel(context.Background())
	inittaskhd             TaskHd
	initonce               sync.Once
)

func init() {
	initEntry()
}

func Init() {
	log.Println(log.DebugLog, "Start routines!")
	initRoutines()

	log.Println(log.DebugLog, "Start http server!")
	InitHttpServer()

	systemServiceTaskRegiste()

	//InitSystemCron()
	//bt.BlueTooth_Init()
	SendSCmd(SCMD_SuperTask_System_BeginInit)

	getSysVol()
	var birthdaySql BirthdaySQL
	err := storage.Config_get(MODULE_CONTROLLER, SQL_KEY_BIRTHDAY, &birthdaySql)
	if nil == err {
		dateNow := GetDateStr()
		if dateNow != birthdaySql.Date {
			birthdaySql.HasCheck = false
			log.Println(log.DebugLog, "dateNow:", dateNow, "  dateSave:", birthdaySql.Date)
		}
	} else {
		birthdaySql.HasCheck = false
	}
	HasCheckBirthdayInfo = birthdaySql.HasCheck

	log.Println(log.DebugLog, "Controller init done!")
}

func InitCtx() {
	initCtx, initCtxCancel = context.WithCancel(context.Background())
}

func GetInitCtx() context.Context {
	InitCtx()
	return initCtx
}

func StartBoard(stage BootStage, isForce bool) {
	bootBoardMutex.Lock()
	defer bootBoardMutex.Unlock()

	if isForce {
		for {
			isExit := false
			select {
			case <-bootBoardChan:
			default:
				isExit = true
			}
			if isExit {
				break
			}
		}
	}
	////CurBootState = stage
	//if CurBootState == stage && CurBootState != BootStage_BACKUPSYSTEM && CurBootState != BootStage_BACKUPSYSTEM_WIFIPARING &&
	//	CurBootState != BootStage_WIFIPARING {
	//	return
	//}
	initCtxCancel()
	TriggerStartBoard(stage)
	//UpdateMicLedsStauts()
}

func StartBoardHasBeenTriggered() bool {
	return false
	if len(bootBoardChan) > 0 {
		return true
	} else {
		return false
	}
}

func SetBootstage(cur BootStage) {
	CurBootState = cur
}

func ToastOtaAfterVersionMessage() {
	vi := GetVersionInfo()
	log.Printf(log.DebugLog, "Toast after new version message: %+v\n", vi)
	switch vi.VuiAfterType {
	case VuiVersionType_Tts:
		schedule.PlayNoticeAsync(AdSrcType_TTS, vi.VuiAfterContent, CONST_AUDIO_ID, false, nil, nil)

	case VuiVersionType_Url:
		schedule.PlayNoticeAsync(AdSrcType_FILE, vi.VuiAfterContent, CONST_AUDIO_ID, false, nil, nil)

	}
}

func ToastOtaBeforeVersionMessage() {
	vi := GetVersionInfo()
	log.Printf(log.DebugLog, "Toast before new version message: %+v\n", vi)
	switch vi.VuiBeforeType {
	case VuiVersionType_Tts:
		schedule.PlayNoticeAsync(AdSrcType_TTS, vi.VuiBeforeContent, CONST_AUDIO_ID, false, nil, nil)

	case VuiVersionType_Url:
		schedule.PlayNoticeAsync(AdSrcType_FILE, vi.VuiBeforeContent, CONST_AUDIO_ID, false, nil, nil)

	}
}

func DoOnceInit() {
	initonce.Do(func() {
		go func() {
			log.Println(log.DebugLog, "Do init once!")

			time.Sleep(500 * time.Millisecond)
			if ShowUpdateVersionInfo == true && LastOtaSource.StartUpToastAfterVui() && SilentBoot == false {
				ShowUpdateVersionInfo = false
				ToastOtaAfterVersionMessage()
			}
			AfterStarupConnectInternet()
		}()
	})
}

func StartBoardRoutine() {
	log.Println(log.DebugLog, "Init board routine started!")
	for {
		select {
		case CurBootState = <-bootBoardChan:
			log.Println(log.DebugLog, "Jump into start board, curboot: ", CurBootState)
			switch CurBootState {
			case BootStage_INIT:
				log.Println(log.DebugLog, "Current stage BootStage_INIT")
				uptime, _ := util.Uptime()
				//wait player online
				log.Println(log.DebugLog, "Wait player module online!")
				//go BtNameInit()
				CurBootState = BootStage_WAITEBOOTDONE
				log.Println(log.DebugLog, "Current stage BootStage_WAITEBOOTDONE")
				if err := WaitBootDone(); err == nil {
					//StartBoard(BootStage_CHECKOTA, true)
					log.Println(log.DebugLog, "wait system boot done success!")
				} else {
					log.Println(log.DebugLog, "Should not come here!!")
				}
				CheckAdb()
				if silent := SilentBootFileCheck(); silent == true {
					SilentBoot = true
				}
				cserveraddr.InitCserveraddr()
				if tmpaddr := cserveraddr.GetServerAddr(); len(tmpaddr) > 0 {
					log.Println(log.ErrorLog, "Begin to set serveraddr:", tmpaddr)
					http.ServerIp = tmpaddr
				}
				for i := 0; ; i++ {
					if IsModOnline(MODULE_PLAYER) {
						break
					} else {
						interfaces.JustSendBusCmd(MODULE_CONTROLLER, MODULE_PLAYER, uint32(C.CMD_SEARCH_PLAYER_REQ))
						time.Sleep(200 * time.Millisecond)
					}

					if time.Duration(i)*200*time.Millisecond > 15*time.Second {
						log.Println(log.DebugLog, "Wait PLAYER > 15 sec, restart player!")
						Modules[MODULE_PLAYER].ServiceRestart()
						i = 0
					}
				}
				log.Println(log.DebugLog, "Player is online!")

				misc.InitVoladc()
				// read cfglist from db
				readCfgList()
				ForceExecCfgListCb()
				//show mute 默认adau静音
				//VolMute(false)
				VolSet(DefaultVol.GetCfgListVui())
				//IconLed_InitPowerUp.Show()
				test.DebugCfgInit()

				playstopch := make(chan int, 1)

				backupLastOtaStatus := GetOTAStatus()
				//Init sql
				//storage.InitSql()

				CurBootState = BootStage_CHECKOTA
				log.Println(log.DebugLog, "Begin check ota if started ", GetOTAStatus())
				//DoRestoreFileToLocal()
				SetOTAStatus(OTAStatus_normal)
				bootmode := CheckOTAStatusWhenBooting()
				log.Println(log.DebugLog, "Check ota finish! bootmode:", bootmode)
				log.Println(log.DebugLog, "Debug git tag:", *GitTag)
				if backupLastOtaStatus == OTAStatus_begin && bootmode == BootMode_NORMAL {
					otaversion := GetVersionInfo()
					log.Println(log.DebugLog, "version in sql:", otaversion.Version)
					if otaversion.Version == *GitTag {
						log.Println(log.DebugLog, "Last should do ota,", bootmode)
						bootmode = BootMode_OTA
					} else {
						log.Println(log.DebugLog, "version is not match, maybe ota fail!")
					}
				}
				log.Println(log.DebugLog, "Finally! bootmode:", bootmode)
				//just for debug
				//bootmode = BootMode_OTA

				switch bootmode {
				case BootMode_NORMAL:
					SendOtaStatusByYunxin(OTAStatus_normal, true, "")
					SetOtaTimes(0)

				case BootMode_OTA:
					IsAfterOtaFirstBoot = true
					DoRestoreFileToLocal()
					SetNightOtaTimes(0)
					ShowUpdateVersionInfo = true
					LastOtaSource = GetOtaSource()
					SetOtaSource(OtaSource_Unknow)
					SendOtaSuccessByYunxin(true, "")
					SetOtaTimes(0)
					eventPoint.EpRecord("B313", map[string]interface{}{"success": true, "NSOSV": GitTag, "src": LastOtaSource})
					if LastOtaSource == OtaSource_NightSilent || LastOtaSource == OtaSource_Force {
						SilentBoot = true
					}

					//debug
					//LastOtaSource = OtaSource_APP

				case BootMode_BACKUPSYSTEM:
					SendOtaStatusByYunxin(OTAStatus_fail, true, "")
					StartBoard(BootStage_BACKUPSYSTEM, true)
					DoRestoreFileToLocal()
					continue
				}

				if SilentBoot == false {
					ctx1, _ := context.WithTimeout(context.Background(), 15*time.Second)
					PlayNoticeAsync(AdSrcType_FILE, SoundNotice_Spinpaiyinyue001.GetPath(), CONST_AUDIO_ID, false, ctx1, func(id uint32, reason NoticeStopReason) {
						if reason.IsStart() {
							return
						}
						playstopch <- 1
					})
				}

				CurBootState = BootStage_BTINIT
				log.Println(log.DebugLog, "Current stage BootStage_BTINIT")
				//bt.BlueTooth_Init()
				//bt.BlueTooth_Off()

				CurBootState = BootStage_CHECKUSER
				log.Println(log.DebugLog, "Current stage BootStage_CHECKUSER")
				var akey string
				err := storage.Config_get(MODULE_CONTROLLER, SQL_KEY_UUID, &Uuid)
				storage.Config_get(MODULE_CONTROLLER, SQL_KEY_AESKEY, &akey)
				if err != nil || len(Uuid) == 0 || len(akey) == 0 {
					log.Println(log.DebugLog, "Init board, this is a new device, jump into wifi paring")
					NewBoard = true
					StartBoard(BootStage_WIFIPARING, true)
					eventPoint.EpRecord("B211", map[string]interface{}{"type": CurWifiParingMode.String(), "net": true})
				} else {
					log.Println(log.DebugLog, "Init board, this is a old device")
					Uuid, BindUser, YxToken, AesKey = GetSqlUUIDS()
					NewBoard = false
					SendUUIDToVE()

					storage.Config_get(MODULE_CONTROLLER, SQL_KEY_OEM_MANUFACTURE, &OemManufature)
					storage.Config_get(MODULE_CONTROLLER, SQL_KEY_TELECOM_CTEI, &CTEI)
				}

				eventPoint.EpRecord("B111", map[string]interface{}{"boottime": uptime, "boot": NewBoard})

				go BtNameInit()
				TellOTABooted()
				if SilentBoot == false {
					log.Println(log.DebugLog, "Begin to wait music stop!")
					<-playstopch
				}

				led_mcu.McuResetInitStatus()

				if NewBoard == false {
					StartBackground_wificheck()
					CurBootState = BootStage_FINISH
					//lupeng add 20180516
					//CurMusicSrcOnOffSt.BtOn = true
					player.OpenBtOfBt()
					EnableBle()
				}

				eventPoint.EpRecord("B113", map[string]interface{}{})
				go ntp.CalTimeUntilSuccess()

			case BootStage_WIFIPARING:
				log.Println(log.DebugLog, "Current stage BootStage_WIFIPARING")
				err := JumpWifiParing(GetInitCtx(), BootStage_DONOTHING)
				log.Println(log.DebugLog, "Exit wifi paring, err:", err)
				switch err {
				case nil:
					CurBootState = BootStage_FINISH
					if tmp := BootDoneCb; tmp != nil {
						go tmp()
						BootDoneCb = nil
					}
					inittaskhd.FinishExec()

				case Err_Interrupted:
					//do nothing, this means that a new status coming
					log.Println(log.DebugLog, "do nothing, this means that a new status coming, do finish wifi paring!")
					if len(bootBoardChan) == 0 {
						CurBootState = BootStage_FINISH
						inittaskhd.FinishExec()
					}

				case Err_Timeout:
					CurBootState = BootStage_FINISH
					inittaskhd.FinishExec()

				default:
					StartBoard(BootStage_WIFIPARING, false)
					eventPoint.EpRecord("B211", map[string]interface{}{"type": CurWifiParingMode.String(), "net": true})
				}

			case BootStage_WAITWIFI:
				log.Println(log.DebugLog, "Current boot stage wait wifi!")
				if err := CheckWifi(GetInitCtx()); err == nil {
					log.Println(log.DebugLog, "Check wifi finish:", err, HasBooted)
					if HasBooted == false {
						StartBoard(BootStage_BEFOREDONE, true)
					} else {
						CurBootState = BootStage_FINISH
					}
				} else {
					log.Println(log.DebugLog, "Check wifi err:", err)
					CurBootState = BootStage_FINISH
				}

			case BootStage_BACKUPSYSTEM:
				log.Println(log.DebugLog, "Current boot stage backup system!")
				if otastatus := GetOTAStatus(); otastatus == OTAStatus_downloading || otastatus == OTAStatus_downloaded || otastatus == OTAStatus_begin {
					log.Println(log.DebugLog, "OTA status and continue ", GetOTAStatus())
					continue
				}

				if len(Uuid) == 0 {
					Uuid, BindUser, YxToken, AesKey = GetSqlUUIDS()
					log.Println(log.DebugLog, "Get user config:", Uuid, BindUser, YxToken, AesKey)
				} else {
					log.Println(log.DebugLog, "has init uuid:", Uuid, BindUser, YxToken, AesKey)
				}

				if len(Uuid) == 0 || len(AesKey) == 0 {
					log.Println(log.ErrorLog, "Can not get right uuid aeskey(backup system),re wifi paring!")
					StartBoard(BootStage_BACKUPSYSTEM_WIFIPARING, true)
					schedule.PlayNoticeSync(AdSrcType_TTS, VUI_BACKUPSYSTEM_UUIDLOST_WIFIPARING, CONST_AUDIO_ID, false, nil)
					continue
				}

				if isSuccess := InBackUpSystem(GetInitCtx()); isSuccess == false {
					log.Println(log.ErrorLog, "Network connect error(backup system), re wifi paring!")
					StartBoard(BootStage_BACKUPSYSTEM_WIFIPARING, true)
					//schedule.PlayNoticeSync(AdSrcType_TTS, VUI_BACKUPSYSTEM_UUIDLOST_WIFIPARING, CONST_AUDIO_ID, false, nil)
					continue
				}

			case BootStage_BACKUPSYSTEM_WIFIPARING:
				log.Println(log.DebugLog, "Current boot stage backup system wifiparing!")
				err := JumpWifiParing(GetInitCtx(), BootStage_DONOTHING)
				log.Println(log.DebugLog, "Exit wifi paring(backup system),err:", err)
				switch err {
				case nil:
					StartBoard(BootStage_BACKUPSYSTEM, true)
				case Err_Interrupted:
					log.Println(log.DebugLog, "wifi paring interrupt!do nothing!")
				default:
					StartBoard(BootStage_BACKUPSYSTEM_WIFIPARING, false)
				}

			case BootStage_BEFOREDONE:
				CurBootState = BootStage_FINISH
				log.Println(log.DebugLog, "Current boot stage before done!", CurBootState)
				//go OTACheckNewVersion()
				//tell OTA bas booted

				log.Println(log.DebugLog, "Boot Done!!!")
				inittaskhd.FinishExec()
			}
		}
	}
	log.Println(log.ErrorLog, "Should not come here, boot can not exit!!!")
}

func TriggerStartBoard(stage BootStage) (success bool) {
	select {
	case bootBoardChan <- stage:
		CurBootState = stage
		if stage == BootStage_BEFOREDONE {
			CurBootState = BootStage_FINISH
		}
		success = true
		log.Println(log.DebugLog, "Next will Jump into ", stage)

	default:
		success = false
		log.Println(log.DebugLog, "Trigger not happen to start board!!")
	}

	return
}

func BtNameInit() {
	for {
		if BTNAME == DEFAULT_DEV_NAME {
			log.Println(log.DebugLog, "Wait bluetooth name!")
			interfaces.JustSendBusCmd(MODULE_CONTROLLER, MODULE_BT, uint32(C.CMD_BT_NAME_GET_REQ))
			time.Sleep(time.Second)
		} else {
			break
		}
	}
}

func IsNewBoard() bool {
	var tmp string
	var err error
	err = storage.Config_get(MODULE_CONTROLLER, SQL_KEY_UUID, &tmp)
	if err != nil || len(tmp) == 0 {
		return true
	}

	//do not check bind user, maybe null in some conditon
	//err = storage.Config_get(MODULE_CONTROLLER, SQL_KEY_BINDUSER, &tmp)
	//if err != nil || len(tmp) == 0 {
	//	return true
	//}

	err = storage.Config_get(MODULE_CONTROLLER, SQL_KEY_AESKEY, &tmp)
	if err != nil || len(tmp) == 0 {
		return true
	}

	err = storage.Config_get(MODULE_CONTROLLER, SQL_KEY_YXTOKEN, &tmp)
	if err != nil || len(tmp) == 0 {
		return true
	}

	return false
}

func SendPing() {
	var ping struct {
		Ping   float64 `json:"PING"`
		TmSec  int64   `json:"tmSec"`
		TmMSec int64   `json:"tmMSec"`
	}

	//log.Println(log.DebugLog, "Send Ping!")
	ping.TmSec = time.Now().Unix()
	ping.TmMSec = (time.Now().UnixNano() / 1e6) % 1000
	data, _ := json.Marshal(ping)
	interfaces.BroadSignalAll(MODULE_CONTROLLER, uint32(C.CMD_MISC_PING), string(data))
}

func systemService_exec(canExec bool, scmd SCMD, arg ...interface{}) {
	if canExec == false {
		log.Println(log.ErrorLog, "Can exec should not false:", canExec)
	}

	log.Println(log.DebugLog, "Current in system service, begin exec cmd:", scmd)
	switch scmd {
	case SCMD_SuperTask_System_BeginInit:
		StartBoard(BootStage_INIT, true)

	case SCMD_SuperTask_System_BeginOta:
		if CurBootState < BootStage_BASEINIT {
			log.Println(log.DebugLog, "Can not begin ota, because system now initing!")
		}
		log.Println(log.DebugLog, "Ota begins, and source:", GetOtaSource())
		switch GetOtaSource() {
		case OtaSource_APP:
			IconLed_Otaing.Show()
			ToastOtaBeforeVersionMessage()

		case OtaSource_Force:
			IconLed_Otaing.Show()
			if getCurDeviceMode(true).IsActive() && IdleTime() < 30*time.Minute {
				ToastOtaBeforeVersionMessage()
				SetOtaSource(OtaSource_Force_Vui)
			}

		case OtaSource_NightSilent:
			if getCurDeviceMode(true).IsActive() && IdleTime() < 30*time.Minute {
				IconLed_Otaing.Show()
				ToastOtaBeforeVersionMessage()
				SetOtaSource(OtaSource_NightSilent_Vui)
			}

		case OtaSource_Force_Vui, OtaSource_NightSilent_Vui:
			log.Println(log.DebugLog, "Should not come here!")
		}

		if tmp := GetOtaSource(); tmp.IsSilent() == true {
			atservice.LampIsShowWhenReset(atservice.MCU_LAMP_INIT_NOT_SHOW, nil)
		}
	}
}

func systemServiceTaskRegiste() {
	var tmp RegistedTask
	var err error

	tmp.Interrupt = func(ByWho string) {
		log.Printf(log.ErrorLog, "I am %s, should by %s interrupt!!\n", tmp.GetName(), ByWho)
	}

	tmp.GetName = func() string {
		return ModuleName_SystemService
	}

	tmp.IsActive = func() bool {
		return (CurBootState != BootStage_FINISH && CurBootState != BootStage_BEFOREDONE && CurBootState != BootStage_WIFIPARING) || CurOTAStatus == OTAStatus_begin
	}

	tmp.GetTaskLevel = func() TaskLevel {
		return TaskLevel_SystemService
	}

	tmp.Resume = func() {
		log.Println(log.DebugLog, "Should not come here, beause nothing can interrupt me!")
	}

	tmp.GetSupportedSCmd = func() []SCMD {
		return []SCMD{SCMD_SuperTask_System_BeginInit,
			SCMD_SuperTask_System_BeginOta}
	}

	tmp.Do = systemService_exec
	tmp.CanBeInterruptByKey = func() bool {
		return false
	}

	tmp.Debug = func() string {
		var tmp string
		tmp += fmt.Sprintf("\n  InternetConnect:%+v\n", InternetConnect)
		tmp += fmt.Sprintln("  Uuid:", Uuid)
		//tmp += fmt.Sprintln("  Aeskey:", AesKey)
		tmp += fmt.Sprintln("  BindUser:", BindUser)
		tmp += fmt.Sprintln("  YxToken:", YxToken)
		tmp += fmt.Sprintln("  BtName:", BTNAME)
		tmp += fmt.Sprintln("  Tag:", *GitTag, " build time:", BuildDate, " Hv:", *Hv)
		tmp += fmt.Sprintln(" OemManufature:", OemManufature, " OemManufactureCheckOk:", OemManufactureCheckOk)
		tmp += fmt.Sprintln("  MicClose:", IsMicClose, "MicCloseTrig:", MicCloseTrig, "IsMicLightOn:", IsMicLightOn)
		tmp += fmt.Sprintf("  cronMic:%+v\n", micControl)
		tmp += fmt.Sprintln(" laststatusicon:", GetLastStatusIcon())
		tmp += fmt.Sprintln(" lasticon:", GetLastIcon())
		tmp += fmt.Sprintf("  Yuxin status:%+v\n", CurYunxinStatus)
		tmp += fmt.Sprintln("  GetOtaSource", GetOtaSource())
		tmp += fmt.Sprintln("  GlobalPause:", GetGlobalPause())
		tmp += fmt.Sprintln("  Last active time:", LastActiveTriggerTime)
		tmp += fmt.Sprintln("  Ota night times:", GetNightOtaTimes())
		tmp += fmt.Sprintln("  CurBootStage:", CurBootState)
		tmp += fmt.Sprintln("  CurOtaStatus:", CurOTAStatus)
		tmp += fmt.Sprintln("  CurWifiStatus:", CurWifiStatus)
		tmp += fmt.Sprintln("  CurSqlWifiMode:", wifi.GetAPstatus())
		tmp += fmt.Sprintln("  CurWifiParingMode:", CurWifiParingMode)
		tmp += fmt.Sprintln("  CurMcuStatus", CurMcuStatus)
		tmp += fmt.Sprintln("  Silent boot:", SilentBoot)
		tmp += fmt.Sprintln("  AlarmDefaultVolum:", DefaultVol.GetCfgListVui())
		tmp += fmt.Sprintln("  HasBooted:", HasBooted)
		tmp += fmt.Sprintln("  NewBoard:", NewBoard)
		tmp += fmt.Sprintln("  Wifi rssi:", GetWifiRssi(), "wifiIP:", WifiIp, "wifimac:", WifiMac)
		tmp += fmt.Sprintln("  Mcu status:", CurMcuStatus)
		tmp += fmt.Sprintln("  Mcu version:", CurMcuVersion)
		tmp += fmt.Sprintln("  ScheduleDomain:", GetCurScheduleDomain())
		tmp += fmt.Sprintln("  Device mode:", getCurDeviceMode(true))
		vol, volerr := adau1761.GetVol()
		tmp += fmt.Sprintln("  Volume:", vol, volerr)
		tmp += fmt.Sprintln(" FirstCalTime:", FirstCalTime)
		tmp += fmt.Sprintln("  CurTime:", time.Now().Local())
		tmp += fmt.Sprintln("  PingTime:", DevNetworkStatus.Time)
		tmp += fmt.Sprintln("  Global cfg list:", GetGlobalCfgList())
		//tmp += fmt.Sprintf(" Get vui configlist:%+v\n", GetCfgListVui())
		//tmp += fmt.Sprintf(" Get time configlist:%+v\n", GetCfgListTime())
		if cron_system != nil {
			for k, entry := range cron_system.Entries() {
				tmp += fmt.Sprintf("  Cron(%d):%+v\n", k, *entry)
			}
		}
		tmp += fmt.Sprintf("  PingStatus:%+v\n", DevNetworkStatus.Ping)
		for _, v := range Modules {
			tmp += fmt.Sprintf("    ModuleName:%25s, Online:%+v, LastActiveTime:%+v\n", v.Aliase, v.Online, v.LastOnlineTime)
		}

		return tmp
	}

	if err, inittaskhd = RegisteSTask(tmp); err == nil {
		log.Println(log.DebugLog, "Registe init task successfully!")
	} else {
		log.Println(log.ErrorLog, "Registe init task fail!")
	}
}

func readCfgList() {
	//var cfglist CfgListType
	//err := ReadCfgList(&cfglist)
	//if nil != err {
	//	log.Println(log.WarningLog, "read cfglist err:", err.Error())
	//	return
	//}
	//SetCfgList(cfglist)

	ReadCfgListMap()
}
