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

namespace ShipyardFileImplement.Implements
{
    public class DetailStorage:IDetailStorage
    {
        private readonly DataFileSingleton source;
        public DetailStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public List<DetailViewModel> GetFullList()
        {
            return source.Details.Select(x => x.GetViewModel).ToList();
        }
        public List<DetailViewModel> GetFilteredList(DetailSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DetailName))
            {
                return new();
            }
            return source.Details
            .Where(x => x.DetailName.Contains(model.DetailName))
            .Select(x => x.GetViewModel)
            .ToList();
        }
        public DetailViewModel? GetElement(DetailSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DetailName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Details
            .FirstOrDefault(x =>
           (!string.IsNullOrEmpty(model.DetailName) && x.DetailName ==
           model.DetailName) ||
            (model.Id.HasValue && x.Id == model.Id))
            ?.GetViewModel;
        }
        public DetailViewModel? Insert(DetailBindingModel model)
        {
            model.Id = source.Details.Count > 0 ? source.Details.Max(x =>x.Id) + 1 : 1;
            var newComponent = Detail.Create(model);
            if (newComponent == null)
            {
                return null;
            }
            source.Details.Add(newComponent);
            source.SaveDetails();
            return newComponent.GetViewModel;
        }
        public DetailViewModel? Update(DetailBindingModel model)
        {
            var component = source.Details.FirstOrDefault(x => x.Id ==
            model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            source.SaveDetails();
            return component.GetViewModel;
        }
        public DetailViewModel? Delete(DetailBindingModel model)
        {
            var element = source.Details.FirstOrDefault(x => x.Id ==
           model.Id);
            if (element != null)
            {
                source.Details.Remove(element);
                source.SaveDetails();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
