package com

import (
	"reflect"

	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"

	"mongo.games.com/game/common"
	rankproto "mongo.games.com/game/protocol/rank"
)

func Register(mainId int, msgType interface{}, h func(s *netlib.Session, g *rankproto.GateTransmit, packetId int, data interface{}, sid int64) error) {
	f := func() interface{} {
		tp := reflect.TypeOf(msgType)
		if tp.Kind() == reflect.Ptr {
			tp = tp.Elem()
		}
		return reflect.New(tp).Interface()
	}

	common.RegisterHandler(mainId, common.HandlerWrapper(func(s *netlib.Session, packetId int, data interface{}, sid int64) error {
		d, ok := data.(*rankproto.GateTransmit)
		if !ok {
			return nil
		}

		msg := f()
		if err := netlib.UnmarshalPacketNoPackId(d.GetPacketData(), msg); err != nil {
			logger.Logger.Errorf("PacketId %v Unmarshal error: %v", mainId, err)
			return err
		}

		if d == nil || d.Platform == "" || d.Platform == "0" || d.Snid == 0 {
			return nil
		}

		return h(s, d, packetId, msg, sid)
	}))

	netlib.RegisterFactory(mainId, netlib.PacketFactoryWrapper(func() interface{} {
		return &rankproto.GateTransmit{}
	}))
}
