package service

import (
	"encoding/json"
	"fmt"

	"github.com/tsmask/go-oam"

	neService "be.ems/src/modules/ne/service"
	neDataModel "be.ems/src/modules/ne_data/model"
	neDataService "be.ems/src/modules/ne_data/service"
	wsService "be.ems/src/modules/ws/service"
)

// 实例化服务层 UENB 结构体
var NewUENB = &UENB{
	neInfoService:  neService.NewNeInfo,
	wsService:      wsService.NewWSSend,
	ueEventService: neDataService.NewUEEvent,
}

// UENB 消息处理
type UENB struct {
	neInfoService  *neService.NeInfo
	wsService      *wsService.WSSend
	ueEventService *neDataService.UEEvent // UE会话事件服务
}

// Resolve 接收处理
func (s *UENB) Resolve(u oam.UENB) error {
	// 是否存在网元
	neInfo := s.neInfoService.FindByRmuid(u.NeUid)
	if neInfo.NeType == "" || neInfo.RmUID != u.NeUid {
		return fmt.Errorf("resolve ue_nb network element does not exist %s", u.NeUid)
	}

	uenbByte, _ := json.Marshal(u)
	uenbEvent := neDataModel.UEEvent{
		NeType:       neInfo.NeType,
		NeName:       neInfo.NeName,
		RmUID:        neInfo.RmUID,
		Timestamp:    u.RecordTime,
		EventType:    u.Type,
		EventJSONStr: string(uenbByte),
	}
	insertId := s.ueEventService.Insert(uenbEvent)
	if insertId <= 0 {
		return fmt.Errorf("add ue_nb data fail")
	}
	uenbEvent.ID = insertId

	// 推送到ws订阅组
	switch neInfo.NeType {
	case "AMF":
		s.wsService.ByGroupID(wsService.GROUP_AMF_UE, uenbEvent)
		s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_AMF_UE, neInfo.NeId), uenbEvent)
	case "MME":
		s.wsService.ByGroupID(wsService.GROUP_MME_UE, uenbEvent)
		s.wsService.ByGroupID(fmt.Sprintf("%s_%s", wsService.GROUP_MME_UE, neInfo.NeId), uenbEvent)
	}
	return nil
}
