package server

import (
	"fmt"
	"game/common/gameService"
	"game/common/proto/pb"
	"game/common/serviceName"
	"game/common/topicName"
	"game/server/match/config"
	"game/server/match/match"
	"github.com/fox/fox/ipb"
	"github.com/fox/fox/log"
	"github.com/fox/fox/service"
	"github.com/golang/protobuf/proto"
)

var Services []*MatchService

type MatchService struct {
	*gameService.GameService
	matchMgr *match.MatchMgr
}

func Init() {
	log.DebugF("init service begin id:%v, num:%v", config.Command.ServiceId, config.Command.ServiceNum)
	for i := 0; i < config.Command.ServiceNum; i++ {
		sid := config.Command.ServiceId + i
		if srv := newService(sid); srv != nil {
			Services = append(Services, srv)
		}
	}
}

func Stop() {
	for _, srv := range Services {
		log.DebugF("notify stop service %v", srv.Name())
		srv.NotifyStop()
	}
	for _, srv := range Services {
		srv.WaitStop()
	}
}

func newService(serviceId int) *MatchService {
	s := new(MatchService)
	s.matchMgr = match.NewMatchMgr()

	sName := fmt.Sprintf("%v-%d", serviceName.Match, serviceId)
	s.GameService = gameService.NewGameService(&service.InitNatsServiceParams{
		EtcdAddress:  config.Cfg.Etcd.Address,
		EtcdUsername: "",
		EtcdPassword: "",
		NatsAddress:  config.Cfg.Nats.Address,
		ServiceType:  serviceName.Match,
		ServiceName:  sName,
		OnFunc:       s,
		TypeId:       int(pb.ServiceTypeId_STI_Match),
		Version:      config.Cfg.BuildDate,
	}, &config.Cfg.Redis)
	_ = s.GameService.Subscribe(topicName.UserOffline)

	s.initProcessor()
	s.OnInit()
	return s
}

func (s *MatchService) OnInit() {
	// if err := s.NatsService.QueueSubscribe(service.GroupTopic(s), service.GroupQueue(s)); err != nil {
	// 	log.Error(err.Error())
	// }
	s.NatsService.Run()
	log.Debug("onInit")
}

func (s *MatchService) CanStop() bool {
	return true
}

func (s *MatchService) OnStop() {
	s.NatsService.OnStop()
	log.Debug("OnStop")
}

// 处理其它服发送过来的消息
func (s *MatchService) OnMessage(data []byte) error {
	var iMsg = &ipb.InternalMsg{}
	var err error
	if err = proto.Unmarshal(data, iMsg); err != nil {
		log.Error(err.Error())
		return err
	}
	if req, err := s.Processor().Unmarshal(iMsg.MsgId, iMsg.Msg); err == nil {
		err = s.Processor().Dispatch(iMsg.MsgId, iMsg, req)
	} else {
		log.Error(err.Error())
	}
	log.Debug(s.Log("received message:%v", pb.MsgId(iMsg.MsgId)))
	return nil
}
