using DressAtelierContracts.BindingModels;
using DressAtelierContracts.SearchModels;
using DressAtelierContracts.StorageContracts;
using DressAtelierContracts.ViewModels;
using DressAtelierFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DressAtelierFileImplement.Implements
{
    public class DressStorage : IDressStorage
    {
        private readonly DataFileSingleton _source;

        public DressStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }

        public List<DressViewModel> GetFullList()
        {
            return _source.Dresses.Select(x => x.GetViewModel).ToList();
        }

        public List<DressViewModel> GetFilteredList(DressSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DressName))
            {
                return new();
            }
            return _source.Dresses.Where(x => x.DressName.Equals(model.DressName)).Select(x => x.GetViewModel).ToList();
        }

        public DressViewModel? GetElement(DressSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DressName) && !model.ID.HasValue)
            {
                return null;
            }

            return _source.Dresses.FirstOrDefault(x => (!string.IsNullOrEmpty(model.DressName) && x.DressName == model.DressName) || (model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
        }

        public DressViewModel? Insert(DressBindingModel model)
        {
            model.ID = _source.Dresses.Count > 0 ? _source.Dresses.Max(x => x.ID) + 1 : 1;
            
            var newDress = Dress.Create(model);
            if (newDress == null)
            {
                return null;
            }
            _source.Dresses.Add(newDress);
            _source.SaveDresses();
            return newDress.GetViewModel;
        }

        public DressViewModel? Update(DressBindingModel model)
        {
            var dress = _source.Dresses.FirstOrDefault(x => x.ID == model.ID);
            if(dress == null)
            {
                return null;
            }
            dress.Update(model);
            _source.SaveDresses();
            return dress.GetViewModel;
        }

        public DressViewModel? Delete(DressBindingModel model)
        {
            var dress = _source.Dresses.FirstOrDefault(x=> x.ID == model.ID);
            if(dress == null)
            {
                return null;
            }
            _source.Dresses.Remove(dress);
            _source.SaveDresses();
            return dress.GetViewModel;
        }
    }
}
