package common

import (
	"fmt"
	"reflect"

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

var handlers = make(map[int]Handler)

type Handler interface {
	Process(s *netlib.Session, packetid int, data interface{}, sid int64) error
}

type HandlerWrapper func(s *netlib.Session, packetid int, data interface{}, sid int64) error

func (hw HandlerWrapper) Process(s *netlib.Session, packetid int, data interface{}, sid int64) error {
	return hw(s, packetid, data, sid)
}

func RegisterHandler(packetId int, h Handler) {
	if _, ok := handlers[packetId]; ok {
		panic(fmt.Sprintf("repeate register handler: %v Handler type=%v", packetId, reflect.TypeOf(h)))
	}

	handlers[packetId] = h
}

func GetHandler(packetId int) Handler {
	if h, ok := handlers[packetId]; ok {
		return h
	}

	return nil
}

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