using System.Collections.Generic;
using Intrepid.Diagnostics;
using Intrepid.Gameplay.Data.Conversion;
using Intrepid.Gameplay.Entities.Player.Sentinel.Events;
using Intrepid.Gameplay.Journey;
using Intrepid.Gameplay.Journey.Messages;
using Intrepid.Integration.Persistence;
using Intrepid.Integration.Persistence.DTOs;

namespace Intrepid.Gameplay.Data
{
    public class SentinelDataStorage : AbstractDataStorage<SentinelDataStorage, SentinelDTO>
    {
        public LatestSaveStationDTO LatestSaveStationData { get; private set; }
        public bool HasLatestSaveStationData => LatestSaveStationData is not null;
        public LoadJourneyRequest LoadJourneyRequest => new()
        {
            StageTag = JourneyService.Instance.GetStageTag(LatestSaveStationData.StageId),
            DeploymentPoint = Converters.Vector3.Unmarshal(LatestSaveStationData.DeploymentPoint),
        };
        
        public void SetLatestSaveStationData(LatestSaveStationEvent e)
        {
            LatestSaveStationData = Converters.LatestSaveStation.Marshal(e);
        }
        
        public override int Order => 0;

        protected override void ValidateDataOrError(List<string> errors)
        {
            ValidateLatestSaveStationEvent();
            
            return;
            
            void ValidateLatestSaveStationEvent()
            {
                if (LatestSaveStationData is null)
                {
                    errors.Add("LatestSaveStationData should not be null");
                    return;
                }
                if (LatestSaveStationData.StageId is null)
                {
                    errors.Add("LatestSaveStationData/StageId should not be null or empty");
                }
                if (LatestSaveStationData.DeploymentPoint is null)
                {
                    errors.Add("LatestSaveStationData/DeploymentPoint should not be null");
                }
            }
        }

        protected override SentinelDTO Marshal()
        {
            return new SentinelDTO
            {
                LatestSaveStation = LatestSaveStationData,
            };
        }

        protected override void Unmarshal(GameDataSlotType slotType, GameSlotDTO gameSlot)
        {
            if (GameDataSlotType.None == slotType)
            {
                DLogger.LogDebug("game slot is empty / running tests?");
                LatestSaveStationData = null;    
                return;
            }
            LatestSaveStationData = gameSlot.SentinelData.LatestSaveStation;
        }
    }
}