using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace ShipyardFileImplement.Implements
{
    public class ShipStorage : IShipStorage
    {
        private readonly DataFileSingleton source;
        public ShipStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public List<ShipViewModel> GetFullList()
        {
            return source.Ships.Select(x => x.GetViewModel).ToList();
        }
        public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ShipName))
            {
                return new();
            }
            return source.Ships.Where(x =>
                x.ShipName.Contains(model.ShipName)).Select(x => x.GetViewModel).ToList();
        }
        public ShipViewModel? GetElement(ShipSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ShipName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Ships.FirstOrDefault(x =>
                (!string.IsNullOrEmpty(model.ShipName) && x.ShipName ==
                model.ShipName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }
        public ShipViewModel? Insert(ShipBindingModel model)
        {
            model.Id = source.Ships.Count > 0 ? source.Ships.Max(x => x.Id) + 1 : 1;
            var newShip = Ship.Create(model);
            if (newShip == null)
            {
                return null;
            }
            source.Ships.Add(newShip);
            source.SaveShips();
            return newShip.GetViewModel;
        }
        public ShipViewModel? Update(ShipBindingModel model)
        {
            var ship = source.Ships.FirstOrDefault(x => x.Id == model.Id);
            if (ship == null)
            {
                return null;
            }
            ship.Update(model);
            source.SaveShips();
            return ship.GetViewModel;
        }
        public ShipViewModel? Delete(ShipBindingModel model)
        {
            var element = source.Ships.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                source.Ships.Remove(element);
                source.SaveShips();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
