package action

import (
	"crm-api/internal/app/ami"
	"crm-api/internal/app/ami/model"
	"errors"
	"strings"
)

func ExtensionStateList() (result []*model.ExtensionStatus, err error) {
	action := map[string]string{
		"Action": "ExtensionStateList",
	}

	res, events, err := ami.AminInstance.Send(action)

	if err != nil {
		return nil, err
	}
	if res["Response"] != "Success" {
		return nil, errors.New(res["Message"])
	}

	for _, event := range events {
		if event.Data["Event"] == "ExtensionStatus" {
			// pjsip web app 三个类型
			// PJSIP/842&PJSIP/wb_842,CustomPresence:842
			hint := event.Data["Hint"]
			end := strings.Index(hint, ",")
			if end > 1 {
				extens := strings.Split(hint[:end], "&")
				//lfshook.NewLogger().Infof("hint %s, extens: %+v", hint, extens)
				for _, exten := range extens {
					if !strings.HasPrefix(exten, "PJSIP") {
						continue
					}
					point := &model.ExtensionStatus{
						Event:      event.Data["Event"],
						Exten:      exten[6:],
						Context:    event.Data["Context"],
						Hint:       hint,
						Status:     event.Data["Status"],
						StatusText: event.Data["StatusText"],
					}
					result = append(result, point)
				}
			}
		}
	}
	return result, nil
}
