package server

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

var Chat []*ChatService

type ChatService struct {
	*gameService.GameService
}

func Init() {
	for i := 0; i < config.Command.ServiceNum; i++ {
		sid := config.Command.ServiceId + i
		if srv := newChatService(sid); srv != nil {
			Chat = append(Chat, srv)
		}
	}
}

func Stop() {
	for _, srv := range Chat {
		srv.NotifyStop()
	}
	for _, srv := range Chat {
		srv.WaitStop()
	}
}

func newChatService(serviceId int) *ChatService {
	var err error
	s := new(ChatService)

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

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

func (s *ChatService) 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 *ChatService) CanStop() bool {
	//log.Debug("chatService.CanStop")
	return true
}

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

// 处理其它服发送过来的消息
func (s *ChatService) 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.UserId, req)
	} else {
		log.Error(err.Error())
	}
	//log.Debug(s.Log("received message:%v", iMsg.MsgId))
	return nil
}
