package service

import (
	"blazing/cool"
	"blazing/modules/blazing/model"
	"encoding/binary"
	"encoding/hex"
	"math/rand"
	"strings"
	"time"

	"github.com/google/uuid"
)

type LoginService struct {
	*cool.Service
}

func NewLoginServiceService() *LoginService {
	return &LoginService{
		&cool.Service{
			Model: model.NewServerList(),
		},
	}
}

// 生成session
func (s *LoginService) GetSessionId(accountID uint) (string, string, error) {

	t1, _ := uuid.NewV7()
	tt := strings.Replace(t1.String(), "-", "", -1)

	rand.NewSource(time.Now().UnixNano())

	// 生成4个随机字节
	bytes := make([]byte, 4)
	for i := range bytes {
		bytes[i] = byte(rand.Intn(256)) // 生成0-255之间的随机数
	}

	buf2 := make([]byte, 4) // 创建4字节的缓冲区
	binary.BigEndian.PutUint32(buf2, uint32(accountID))

	//fmt.Printf("小端序: %v (十六进制: %x)\n", buf2, buf2) // 输出: [252 255 255 255] (0xFCFFFFFF)
	ttid, _ := hex.DecodeString(tt)
	//fmt.Println(bytes, "随机字节")
	ret := append(buf2, ttid...)
	ret = append(ret, bytes...)

	return hex.EncodeToString(ret), tt, nil
	// /t1.
	// 以上过程只需全局一次，且应在生成ID之前完成。
}
func (s *LoginService) SetServerID(OnlineID uint16, Port uint16, t *struct {
	Kick func(uint32) error

	RegisterLogic func(uint16, uint16) error
}) error {

	m := cool.DBM(s.Model).Where("online_id", OnlineID)

	record, err := m.One()
	if err != nil {
		return err
	}
	if record == nil {
		//说明是新的服务器

		_, err := m.InsertAndGetId(&model.ServerList{OnlineID: OnlineID, Port: Port})

		return err
	}
	var tttt model.ServerList
	record.Struct(&tttt)
	//t.Quit(int32(tttt.Port))
	_, err = m.Data(&model.ServerList{OnlineID: OnlineID, Port: Port}).Where("online_id", OnlineID).Update()

	return nil

}
