package handler

import (
	"log"
	"strings"

	"git.lxtend.com/qqbot/model"
)

type Handler func(msg model.Message) (reply model.Reply)

var handlers = make(map[string]Handler)
var liveHandlers = make(map[int64]map[int64]Handler)
var privateAllHandler Handler

func RegisterPrivateHandler(handler Handler) {
	privateAllHandler = handler
}

func RegisterHandler(trigger string, handler Handler) {
	handlers[trigger] = handler
}

func RegisterLiveHandler(groupID int64, userID int64, handler Handler) { //userID=-1 means for all users in groupID
	if _, ok := liveHandlers[groupID]; !ok {
		liveHandlers[groupID] = make(map[int64]Handler)
	}
	liveHandlers[groupID][userID] = handler
}

func MsgInHandler(msg model.Message) (reply model.Reply) {
	defer func() {
		if r := recover(); r != nil {
			log.Default().Printf("Recovered in MsgInHandler: %v", r)
		}
	}()
	if msg.Msg != "" {
		log.Default().Printf("M:%v", msg)
	} else {
		return model.Reply{}
	}
	defer func() {
		if reply.ReplyMsg != "" {
			log.Default().Printf("R:%v", reply)
		}
	}()
	if handlerUserID, ok := liveHandlers[msg.GroupInfo.GroupId]; ok {
		if handler, ok := handlerUserID[msg.UserId]; ok {
			liveHandlers[msg.GroupInfo.GroupId][msg.UserId] = nil
			return handler(msg)
		}
	}
	msgArray := strings.Split(msg.Msg, " ")
	if handler, ok := handlers[msgArray[0]]; ok {
		return handler(msg)
	}
	if !msg.GroupInfo.IsGroupMsg && privateAllHandler != nil {
		return privateAllHandler(msg)
	}
	return model.Reply{}
}
