package server

import (
	"fmt"
	"game/common/proto/pb"
	"game/common/serviceName"
	"game/server/db/config"
	"github.com/fox/fox/log"
	"github.com/fox/fox/service"
)

var DbSrv []*DbService

type DbService struct {
	*service.NatsService
}

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 := newDbService(sid); srv != nil {
			DbSrv = append(DbSrv, srv)
		}
	}
}

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

func newDbService(serviceId int) *DbService {
	var err error
	s := new(DbService)

	sName := fmt.Sprintf("%v-%d", serviceName.Db, serviceId)
	if s.NatsService, err = service.NewNatsService(&service.InitNatsServiceParams{
		EtcdAddress:  config.Cfg.Etcd.Address,
		EtcdUsername: "",
		EtcdPassword: "",
		NatsAddress:  config.Cfg.Nats.Address,
		ServiceType:  serviceName.Db,
		ServiceName:  sName,
		OnFunc:       s,
		TypeId:       int(pb.ServiceTypeId_STI_DB),
		Version:      config.Cfg.BuildDate,
	}); err != nil {
		log.Fatal(err.Error())
		return nil
	}

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

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

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

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