package emoji

import (
	"fmt"
	emojiCfg "server/conf/emoji"
	GoUtil "server/game_util"
	"server/msg"
)

type EmojiMod struct {
	List map[int]*Emoji
	Set  map[int]int
}

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

const (
	EMOJI_TYPE_GREETING = iota
	EMOJI_TYPE_HAPPY
	EMOJI_TYPE_TAUNT
	EMOJI_TYPE_FAIL
)

func (e *EmojiMod) InitData() {
	now := GoUtil.Now()
	if e.Set == nil {
		e.Set = make(map[int]int)
	}
	if e.List == nil {
		InitId := emojiCfg.GetInitList()
		e.List = make(map[int]*Emoji, len(InitId))
		for _, v := range InitId {
			e.List[v] = &Emoji{
				AddTime: now,
			}
		}
	}
}

func (e *EmojiMod) GetEmojiNum() int {
	return len(e.List)
}

// 设置表情，Id为0表示清空该类型表情
func (e *EmojiMod) SetEmoji(Id, Type int) error {
	if Id == 0 {
		e.Set[Type] = Id
		return nil
	}
	if _, ok := e.List[Id]; !ok {
		return fmt.Errorf("emoji id not exist")
	}
	e.Set[Type] = Id
	return nil
}

// 解锁表情，Time为解锁时长，单位为秒
func (e *EmojiMod) Unlock(Id, Time int) error {
	v, ok := e.List[Id]
	if ok {
		if v.Ts == 0 {
			return nil
		}
		v.Ts += int64(Time)
		return nil
	}
	now := GoUtil.Now()
	e.List[Id] = &Emoji{
		Ts:      now + int64(Time),
		AddTime: now,
	}
	return nil
}

// 获取表情列表
func (e *EmojiMod) GetEmojiSet() map[int32]int32 {
	return GoUtil.MapIntToInt32(e.Set)

}

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