package base

import (
	"encoding/json"
	"os"
	"time"

	"github.com/globalsign/mgo/bson"
	"mongo.games.com/goserver/core"
	"mongo.games.com/goserver/core/logger"

	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
)

type AccountData struct {
	Acc    string
	Create int64
	Time   time.Time
}

var (
	// 待使用的账号，将要建立连接
	accChan = make(map[string]bool)
	// 账号池，当前正在使用的机器人
	accPool []*AccountData
)
var accountFileName = "robotaccount.json"

func init() {
	model.InitGameParam()

	core.RegisteHook(core.HOOK_BEFORE_START, func() error {
		initAccountData()
		// 连接数据库服务
		model.StartupRPClient(common.CustomConfig.GetString("MgoRpcCliNet"), common.CustomConfig.GetString("MgoRpcCliAddr"), time.Duration(common.CustomConfig.GetInt("MgoRpcCliReconnInterV"))*time.Second)
		return nil
	})
}

// 初始化机器人账号
func initAccountData() {
	dirty := false
	newFunc := func(n int) {
		for i := 0; i < n; i++ {
			accId := bson.NewObjectId().Hex()
			accPool = append(accPool, &AccountData{
				Acc:    accId,
				Create: time.Now().UnixNano(),
				Time:   time.Now(),
			})
		}
		dirty = true
	}

	fileData, err := os.ReadFile(accountFileName)
	if err != nil {
		logger.Logger.Error("Read robot account file error:", err)
		//没有账号文件，创建新的一组账号
		newFunc(Config.Count)
	} else {
		if err := json.Unmarshal(fileData, &accPool); err != nil {
			logger.Logger.Error("Unmarshal robot account data error:", err)
			//账号文件数据反序列化失败，创建新的账号数据
			newFunc(Config.Count)
		} else {
			//核对文件中的账号数量
			if len(accPool) < Config.Count {
				//数量过少，添加一部分账号
				newFunc(Config.Count - len(accPool))
			}
		}
	}

	for i := 0; i < Config.Count; i++ {
		accChan[accPool[i].Acc] = true
	}

	if dirty {
		//持久化本次的账号数据
		buff, err := json.Marshal(accPool)
		if err != nil {
			logger.Logger.Error("Marshal account data error:", err)
		} else {
			err := os.WriteFile(accountFileName, buff, os.ModePerm)
			if err != nil {
				logger.Logger.Error("Write robot account file error:", err)
			}
		}
	}
}
