package service

import (
	"fmt"
	"time"

	"be.ems/src/framework/utils/date"
	"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"
)

// 实例化服务层 NBState 结构体
var NewNBState = &NBState{
	neInfoService:  neService.NewNeInfo,
	wsService:      wsService.NewWSSend,
	nbStateService: neDataService.NewNBState,
}

// NBState 消息处理
type NBState struct {
	neInfoService  *neService.NeInfo
	wsService      *wsService.WSSend
	nbStateService *neDataService.NBState
}

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

	nbState := neDataModel.NBState{
		NeType:   neInfo.NeType,
		NeId:     neInfo.NeId,
		RmUid:    neInfo.RmUID,
		Address:  n.Address,
		Name:     n.Name,
		Position: n.Position,
		NbName:   n.DeviceName,
		State:    n.State,
		Time:     date.ParseDateToStr(n.StateTime, time.RFC3339),
	}
	insertId := s.nbStateService.Insert(nbState)
	if insertId <= 0 {
		return fmt.Errorf("add nb_state data fail")
	}
	nbState.ID = insertId

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