package service

import (
	"encoding/json"
	"fmt"

	"be.ems/src/framework/vo/result"
	"be.ems/src/modules/ws/model"
)

// 订阅组指定编号为支持服务器向客户端主动推送数据
const (
	// 组号-其他
	GROUP_OTHER = "0"
	// 组号-指标
	GROUP_KPI = "10"
	// 组号-指标UPF
	GROUP_KPI_UPF = "12"
	// 组号-IMS_CDR会话事件
	GROUP_IMS_CDR = "1005"
	// 组号-AMF_UE会话事件
	GROUP_AMF_UE = "1010"
)

// 实例化服务层 WSSendImpl 结构体
var NewWSSendImpl = &WSSendImpl{}

// IWSSend WebSocket消息发送处理 服务层处理
type WSSendImpl struct{}

// ByClientID 给已知客户端发消息
func (s *WSSendImpl) ByClientID(clientID string, data any) error {
	v, ok := WsClients.Load(clientID)
	if !ok {
		return fmt.Errorf("no fount client ID: %s", clientID)
	}

	dataByte, err := json.Marshal(result.OkData(data))
	if err != nil {
		return err
	}

	client := v.(*model.WSClient)
	if len(client.MsgChan) > 90 {
		NewWSImpl.CloseClient(client.ID)
		return fmt.Errorf("msg chan over 90 will close client ID: %s", clientID)
	}
	client.MsgChan <- dataByte
	return nil
}

// ByGroupID 给订阅组的用户发送消息
func (s *WSSendImpl) ByGroupID(groupID string, data any) error {
	uids, ok := WsGroup.Load(groupID)
	if !ok {
		return fmt.Errorf("no fount Group ID: %s", groupID)
	}

	groupUids := uids.(*[]string)
	// 群组中没有成员
	if len(*groupUids) == 0 {
		return fmt.Errorf("no members in the group")
	}

	// 在群组中找到对应的 uid
	for _, uid := range *groupUids {
		clientIds, ok := WsUsers.Load(uid)
		if !ok {
			continue
		}
		// 在用户中找到客户端并发送
		uidClientIds := clientIds.(*[]string)
		for _, clientId := range *uidClientIds {
			err := s.ByClientID(clientId, map[string]any{
				"groupId": groupID,
				"data":    data,
			})
			if err != nil {
				continue
			}
		}
	}

	return nil
}
