package mail

import (
	"fmt"
	"server/GoUtil"
	"server/game/mod/item"
	"server/msg"
)

type MailMod struct {
	List       map[int]*MailInfo // 邮件列表
	AutoId     int               // 自增id
	ServerMail []int
}

const (
	MAIL_STATUS_IDLE   = 0
	MAIL_STATUS_READ   = 1
	MAIL_STATUS_REWARD = 2
	MAIL_STATUS_DEL    = 3
)

type MailInfo struct {
	Title   string       // 邮件标题
	Content string       // 邮件内容
	Items   []*item.Item // 邮件道具
	Type    int          //邮件类型
	Send    int64        // 发送时间
	Del     int64        // 删除时间
	Status  int
}

func (m *MailMod) InitData() {
	if m.List == nil {
		m.List = make(map[int]*MailInfo)
	}
}

// 发送邮件
func (m *MailMod) Send(Title, Content string, Items []*item.Item) int {
	m.AutoId++
	m.List[m.AutoId] = &MailInfo{
		Title:   Title,
		Content: Content,
		Items:   Items,
		Send:    GoUtil.Now(),
	}
	return m.AutoId
}

// 阅读邮件
func (m *MailMod) Read(id int) error {
	v, ok := m.List[id]
	if !ok {
		return fmt.Errorf("mail id %d not exist", id)
	}
	if v.Status == MAIL_STATUS_IDLE {
		v.Status = MAIL_STATUS_READ
	}
	return nil
}

// 领取邮件奖励
func (m *MailMod) Reward(id int) ([]*item.Item, error) {
	v, ok := m.List[id]
	if !ok {
		return nil, fmt.Errorf("mail id %d not exist", id)
	}
	if v.Status != MAIL_STATUS_IDLE {
		return nil, fmt.Errorf("mail not readed")
	}
	v.Status = MAIL_STATUS_REWARD
	return v.Items, nil
}

// 删除邮件
func (m *MailMod) Del(id int) error {
	v, ok := m.List[id]
	if !ok {
		return fmt.Errorf("mail id %d not exist", id)
	}
	if v.Status == MAIL_STATUS_DEL {
		return fmt.Errorf("mail have readed")
	}
	v.Status = MAIL_STATUS_DEL
	v.Del = GoUtil.Now()
	return nil
}

func (m *MailMod) BackData() *msg.ResMailList {
	res := &msg.ResMailList{
		MailList: make(map[int32]*msg.MailInfo),
	}
	for k, v := range m.List {
		res.MailList[int32(k)] = &msg.MailInfo{
			Id:      int32(k),
			Title:   v.Title,
			Content: v.Content,
			Items:   item.ItemToMsg(v.Items),
			Status:  int32(v.Status),
			Time:    int32(v.Send),
		}
	}
	return res
}

func (m *MailMod) NotifyMail(Id int) *msg.MailNotify {
	mailInfo := m.List[Id]
	return &msg.MailNotify{
		Info: &msg.MailInfo{
			Id:      int32(Id),
			Title:   mailInfo.Title,
			Content: mailInfo.Content,
			Items:   item.ItemToMsg(mailInfo.Items),
			Status:  int32(mailInfo.Status),
			Time:    int32(mailInfo.Send),
		},
	}
}
