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 k, v := range f.List {
		if v.AddTime == 0 {
			v.AddTime = RegisterTime
			f.List[k] = v
		}
	}
}

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

func (f *FaceMod) SetFace(Id int) error {
	if Id == 0 {
		f.SetId = Id
		return nil
	}
	if _, ok := f.List[Id]; !ok {
		return fmt.Errorf("face id not exist")
	}
	f.SetId = Id
	return nil
}

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

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