package msg

import (
	"fmt"
	"os"
	"reflect"
	"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(&Hello{})
	Processor.Register(&ReqLogin{})
	Processor.Register(&ResLogin{})
	Processor.Register(&EnterHall{})
	Processor.Register(&LeaveHall{})
	Processor.Register(&ResJoinRoom{})
	Processor.Register(&ReqJoinRoom{})
	Processor.Register(&PlayList{})
	Processor.Register(&Shop{})
	Processor.Register(&ReqGameInfo{})
	Processor.Register(&ResGameInfo{})
	Processor.Register(&TeenPattiRoomList{})
	Processor.Register(&TeenPattiRoom{})
	Processor.Register(&ReqDealCard{})
	Processor.Register(&ReqPlayerAction{})
	Processor.Register(&ResPlayerOptAction{})
	// Processor.Register(&PlayerOptType{})
	// Processor.Register(&PlayerOpt{})
	Processor.Register(&ReqRound{})
	Processor.Register(&ReqBet{})
	// Processor.Register(&MsgError{})
	Processor.Register(&ReqPlayerList{})
	Processor.Register(&ReqResult{})
	Processor.Register(&ReqRoomTipsMessage{})
	Processor.Register(&ReqHeartBeat{})
	Processor.Register(&ResHeartBeat{})
	Processor.Register(&NextRound{})
	Processor.Register(&ReqLeaveRoom{})
	Processor.Register(&ReqUserInfo{})
	Processor.Register(&SiteShowResult{})
	Processor.Register(&ReqInsufficientPoints{})

	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")

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