package msg

import (
	"fmt"
	"os"
	"reflect"
	"server/tools"
	"strings"

	"github.com/name5566/leaf/log"
	"github.com/name5566/leaf/network/protobuf"
)

var Processor = protobuf.NewProcessor()

type MsgInfo struct {
	ID   uint16
	Name string
}

var msgList []MsgInfo

func init() {
	Processor.Register(&ReqLogin{})
	Processor.Register(&ResLogin{})
	Processor.Register(&ReqRegister{})
	Processor.Register(&ResRegister{})
	Processor.Register(&EnterHall{})
	Processor.Register(&ResEnterHall{})
	Processor.Register(&LeaveHall{})
	Processor.Register(&ResHeartBeat{})
	Processor.Register(&ReqHeartBeat{})
	Processor.Register(&SendColorSz{})
	Processor.Register(&SendRoleMove{})
	Processor.Register(&SendQuitRoom{})
	Processor.Register(&NotifyPlayerSzNumber{})
	Processor.Register(&NotifyPlayerMove{})
	Processor.Register(&NotifyPlayerOpt{})
	Processor.Register(&NotifyPlayerStatus{})
	Processor.Register(&NotifySettlement{})
	Processor.Register(&MatchLudo{})
	Processor.Register(&ResMatchLudo{})
	Processor.Register(&NotifyUpdateRoomInfo{})
	Processor.Register(&BeKickLogin{})
	Processor.Register(&UpdateUserInfo{})
	Processor.Register(&ReqShop{})
	Processor.Register(&ResShop{})
	Processor.Register(&BuyShopItem{})
	Processor.Range(func(id uint16, t reflect.Type) {
		log.Debug("消息ID: %d, 消息类型: %s\n", id, t.Elem().Name())
		msgList = append(msgList, MsgInfo{
			ID:   id,
			Name: t.Elem().Name(),
		})
		// fmt.Printf("消息ID: %d, 消息类型: %s\n", id, t.Elem().Name())
	})
	generateTSCode()
}

func generateTSCode() {
	var tsCode strings.Builder
	tsCode.WriteString("// 自动生成的消息ID映射\n")
	tsCode.WriteString("export enum MsgID {\n")

	for _, msg := range msgList {
		tsCode.WriteString(fmt.Sprintf("    %s = %d,\n", msg.Name, msg.ID))
	}

	tsCode.WriteString("}\n")

	var path = "/home/ludo_server/bin/client_msg/msg.ts"
	if tools.IsDebug {
		path = "/Users/xy/Desktop/ludo_server/bin/client_msg/msg.ts"
	}

	// 写入文件
	err := os.WriteFile(path, []byte(tsCode.String()), 0644)
	if err != nil {
		log.Error("生成 TypeScript 代码失败: %v", err)
	}
}
