package status

import (
	"crm-api/internal/app/ami/action"
	"crm-api/internal/app/redis"
	"crm-api/pkg/lfshook"
	"strings"
)

// InitAsterisk 初始化状态
func InitAsterisk() {

	// 清空存在的状态
	redis.ExtensionClean()

	// PJSIPShowContacts 查询注册状态
	data, err := action.PJSIPShowContacts()
	if err != nil {
		lfshook.NewLogger().Errorf("PJSIPShowContacts error %+v", err)
		return
	}
	extens := make([]string, 0)

	// core show contacts
	for _, point := range data {
		exten := strings.Split(point.ObjectName, ";")[0]
		exten = strings.TrimSpace(exten)
		addr := point.ViaAddr
		// 远程注册 addr 不能取 ViaAddr, 通过 uri 获取
		info := strings.Split(point.Uri, "@")
		if len(info) == 2 {
			addr = strings.Split(info[1], ":")[0]
		}

		redis.ExtensionSet(exten, point.Uri, addr, point.RoundtripUsec)
		extens = append(extens, exten)
	}

	initDNDStatus(&extens)
	initExtensionStatus()

	// 触发任务可能修改了文件
	// go action.Command("dialplan reload")
}

func initDNDStatus(extensions *[]string) {
	for _, extension := range *extensions {
		value, _ := action.DBGet("DND", extension)
		if value != "" {
			redis.ExtensionDNDSet(extension, value)
		}
	}
}

func initExtensionStatus() {
	events, err := action.ExtensionStateList()
	if err != nil {
		lfshook.NewLogger().Error(err)
		return
	}
	for _, event := range events {
		//lfshook.NewLogger().Infof("init event %+v", event)
		redis.ExtensionSetStatus(event)
	}
}
