package avatar

import (
	"fmt"
	avatarCfg "server/conf/avatar"
	GoUtil "server/game_util"
	"server/msg"
)

type AvatarMod struct {
	List  map[int]*Avatar
	SetId int
}

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

func (f *AvatarMod) Login(RegisterTime int64) {
	for k, v := range f.List {
		if v.AddTime == 0 {
			v.AddTime = RegisterTime
			f.List[k] = v
		}
	}
}
func (a *AvatarMod) InitData() {
	now := GoUtil.Now()
	if a.List == nil {
		InitId := avatarCfg.GetInitList()
		a.List = make(map[int]*Avatar, len(InitId))
		for _, v := range InitId {
			a.List[v] = &Avatar{
				AddTime: now,
			}
		}
	}
}

func (a *AvatarMod) GetAvatarNum() int {
	return len(a.List)
}

func (a *AvatarMod) SetAvatar(Id int) error {
	if _, ok := a.List[Id]; !ok {
		return fmt.Errorf("avatar id:%d not exist", Id)
	}
	a.SetId = Id
	return nil
}

func (a *AvatarMod) 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()
	ts := int64(0)
	if Time > 0 {
		ts = now + int64(Time)
	}
	a.List[Id] = &Avatar{
		Ts:      ts,
		AddTime: now,
	}
	return nil
}

func (a *AvatarMod) BackData() []*msg.AvatarInfo {
	l := make([]*msg.AvatarInfo, 0, len(a.List))
	for k, v := range a.List {
		l = append(l, &msg.AvatarInfo{
			Id:      int32(k),
			EndTime: v.Ts,
			AddTime: v.AddTime,
		})
	}
	// 返回数据
	return l
}
