package controller

import (
	"blazing/common/socket/errorcode"
	"blazing/logic/service"
	"blazing/logic/service/maphot"
	"blazing/logic/service/maps"
	"blazing/logic/service/space"
	"time"

	"github.com/jinzhu/copier"
)

func (h *Controller) MapEnter(data *maps.InInfo, c *service.Player) (result *maps.OutInfo, err errorcode.ErrorCode) { //这个时候player应该是空的

	c.Info.MapID = data.MapId                          //登录地图
	space.GetSpace(c.Info.MapID).Set(c.Info.UserID, c) //添加玩家
	result = maps.NewOutInfo()
	c.Info.Pos = data.Point
	copier.Copy(result, c.Info)

	data.Broadcast(c.Info.MapID, *result) //同步广播
	// 如果是无怪地图，直接返回
	if c.StopChan != nil {
		close(c.StopChan)
		c.StopChan = nil
	}
	// 创建新的停止通道
	c.StopChan = make(chan struct{})

	// 启动刷怪协程
	go func(stopChan chan struct{}, currentMap int) {

		<-time.After(5 * time.Second)
		// 首次刷新
		if c.FightC == nil && c.Info.MapID != 0 {
			data.SpawnMonsters(c, true)
		}
		//循环刷新怪物

		ticker := time.NewTicker(10 * time.Second)
		defer ticker.Stop()

		for {
			select {
			case <-stopChan:
				// 收到停止信号，退出协程
				return
			case <-ticker.C:
				// 刷新当前地图的怪物
				if c.FightC == nil && c.Info.MapID != 0 {
					data.SpawnMonsters(c, false)
				}

			}
		}
	}(c.StopChan, int(c.Info.MapID))
	return nil, -1
}
func (h Controller) MapHot(data *maphot.InInfo, c *service.Player) (result *maphot.OutInfo, err errorcode.ErrorCode) {

	result = &maphot.OutInfo{

		HotInfos: space.GetMapHot(),
	}

	return
}
func (h *Controller) MapLeave(data *maps.LeaveMapInboundInfo, c *service.Player) (result *maps.LeaveMapOutboundInfo, err errorcode.ErrorCode) { //这个时候player应该是空的
	//result = &maps.LeaveMapOutboundInfo{UserID: c.GetUserID()}

	data.Broadcast(c.Info.MapID, maps.LeaveMapOutboundInfo{UserID: c.Info.UserID}) //同步广播
	space.GetSpace(c.Info.MapID).Delete(c.Info.UserID)
	// 如果有正在运行的刷怪协程，发送停止信号
	if c.StopChan != nil {
		close(c.StopChan)
		c.StopChan = nil
	}
	c.Info.MapID = 0 // 重置当前地图
	return nil, -1
}
func (h *Controller) MapList(data *maps.ListMapPlayerInboundInfo, c *service.Player) (result *maps.ListMapPlayerOutboundInfo, err errorcode.ErrorCode) { //这个时候player应该是空的

	result = &maps.ListMapPlayerOutboundInfo{}
	result.Player = make([]maps.OutInfo, 0)

	space.GetSpace(c.Info.MapID).Range(func(userID uint32, player service.PlayerI) bool {
		result1 := maps.NewOutInfo()
		copier.Copy(result1, player)
		result.Player = append(result.Player, *result1)
		return true
	})

	return
}
