package face

import (
	"fmt"
	faceCfg "server/conf/face"
	GoUtil "server/game_util"
	"server/msg"
)

type FaceMod struct {
	List  map[int]*Face
	SetId int
}

type Face struct {
	Ts      int64 // 过期时间 0表示永久
	AddTime int64
}

func (f *FaceMod) Login(RegisterTime int64) {
	for _, v := range f.List {
		if v.AddTime == 0 {
			v.AddTime = RegisterTime
		}
	}
}

func (f *FaceMod) InitData() {
	now := GoUtil.Now()
	if f.List == nil {
		f.List = make(map[int]*Face)
		f.SetId = 1
	}
	InitId := faceCfg.GetInitList()
	for _, v := range InitId {
		if _, ok := f.List[v]; ok {
			continue
		}
		// 初始化表情
		f.List[v] = &Face{
			AddTime: now,
		}
	}
}

// 获取表情数量
func (f *FaceMod) GetFaceNum() int {
	return len(f.List)
}

// 设置表情，Id为0表示清空表情
func (f *FaceMod) SetFace(Id int) error {
	if Id != 0 {
		if _, ok := f.List[Id]; !ok {
			return fmt.Errorf("face id not exist")
		}
	}
	f.SetId = Id
	return nil
}

// 解锁表情
func (f *FaceMod) Unlock(Id, Time int) error {
	v, ok := f.List[Id]
	if ok {
		if v.Ts == 0 {
			return nil
		}
		v.Ts += int64(Time)
		return nil
	}
	now := GoUtil.Now()
	f.List[Id] = &Face{
		Ts:      now + int64(Time),
		AddTime: now,
	}
	return nil
}

func (f *FaceMod) BackData() []*msg.FaceInfo {
	l := make([]*msg.FaceInfo, 0, len(f.List))
	for k, v := range f.List {
		l = append(l, &msg.FaceInfo{
			Id:      int32(k),
			EndTime: v.Ts,
			AddTime: v.AddTime,
		})
	}
	return l
}
