using System.Collections.Generic;
using BattleIce;

namespace ET.Server
{
    public class PlayerTempDataComponentAwakeSystem: AwakeSystem<PlayerTempDataComponent, WNPlayer>
    {
        /// <summary>
        /// 玩家临时数据组件创建
        /// </summary>
        /// <param name="self"></param>
        /// <param name="player"></param>
        protected override void Awake(PlayerTempDataComponent self, WNPlayer player)
        {
            self.Player = player;
        }
    }

    public class PlayerTempDataComponentDestroySystem: DestroySystem<PlayerTempDataComponent>
    {
        /// <summary>
        /// 玩家临时数据组件销毁
        /// </summary>
        /// <param name="self"></param>
        protected override void Destroy(PlayerTempDataComponent self)
        {
            self?.Save();
        }
    }

    [FriendOf(typeof (PlayerTempDataComponent))]
    public static class PlayerTempDataComponentSystem
    {
        public static async ETTask InitFromDB(this PlayerTempDataComponent self)
        {
            List<PlayerMapInfo> list = await DBManagerComponent.Instance.GetZoneDB(self.DomainZone())
                    .Query<PlayerMapInfo>(p => p.Id == self.Player.GetId());
            if (list is { Count: > 0 })
            {
                self.MapData = list[0];
            }
            else
            {
                self.MapData = new PlayerMapInfo();
                self.MapData.mapId = 10098;
                await self.Save();
            }
        }

        public static async ETTask Save(this PlayerTempDataComponent self)
        {
            if (self.MapData != null)
            {
                await DBManagerComponent.Instance.GetZoneDB(self.DomainZone()).Save(self.MapData);
            }
        }

        /** 同步场景出生数据 **/
        public static void SyncBornData(this PlayerTempDataComponent self, float bornX, float bornY, int bornAreaId)
        {
            self.MapData.bornX = bornX;
            self.MapData.bornY = bornY;
            self.MapData.bornMapId = bornAreaId;
        }

        /** 同步场景临时数据 **/
        public static void SyncNowData(this PlayerTempDataComponent self, int areaId, long instanceId, GetPlayerData data)
        {
            self.MapData.x = data.x;
            self.MapData.y = data.y;
            self.MapData.direction = data.direction;
            self.MapData.hp = data.hp;
            self.MapData.mp = data.mp;
            self.MapData.mapId = areaId;
            self.MapData.mapInstanceId = instanceId;
        }

        /** 同步场景历史数据 **/
        public static void SyncHistoryData(this PlayerTempDataComponent self, MapConfig prop, long instanceId, GetPlayerData data)
        {
            self.MapData.historyX = data.x;
            self.MapData.historyY = data.y;
            self.MapData.historyDirection = data.direction;
            self.MapData.historyMapId = prop.Id;
            self.MapData.historyMapInstanceId = instanceId;
        }

    }
}