package servicex

import (
	"fmt"
	"game/common/gameService"
	"game/common/proto/pb"
	"game/common/serviceName"
	config "github.com/flipped-aurora/gin-vue-admin/server/configx"
	"github.com/fox/fox/log"
	"github.com/fox/fox/service"
	"github.com/fox/fox/xrand"
)

var servers []*AdminService

type AdminService struct {
	*gameService.GameService
}

func GetService() *AdminService {
	idx := xrand.RandN(len(servers))
	return servers[idx]
}

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 {
			servers = append(servers, srv)
		}
	}
}

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

func newService(serviceId int) *AdminService {
	s := new(AdminService)

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

	//s.initRpcProcessor()
	s.OnInit()
	return s
}

func (s *AdminService) 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 *AdminService) CanStop() bool {
	return true
}

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

// 处理其它服发送过来的消息
func (s *AdminService) OnMessage(data []byte) error {
	_ = data
	return nil
}
