using GarmentFactoryContracts.BindingModels;
using GarmentFactoryContracts.SearchModels;
using GarmentFactoryContracts.StoragesContracts;
using GarmentFactoryContracts.ViewModels;
using GarmentFactoryFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GarmentFactoryFileImplement.Implements
{
    public class TextileStorage : ITextileStorage
    {
        private readonly DataFileSingleton source;

        public TextileStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

        public List<TextileViewModel> GetFullList()
        {
            return source.Textils
                    .Select(x => x.GetViewModel)
                    .ToList();
        }

        public List<TextileViewModel> GetFilteredList(TextileSearchModel model)
        {
            if (string.IsNullOrEmpty(model.TextileName))
            {
                return new();
            }
            return source.Textils
                    .Where(x => x.TextileName.Contains(model.TextileName))
                    .Select(x => x.GetViewModel)
                    .ToList();
        }

        public TextileViewModel? GetElement(TextileSearchModel model)
        {
            if (string.IsNullOrEmpty(model.TextileName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Textils
                    .FirstOrDefault(x => (!string.IsNullOrEmpty(model.TextileName) && x.TextileName == model.TextileName) ||
                                        (model.Id.HasValue && x.Id == model.Id))
                    ?.GetViewModel;
        }

        public TextileViewModel? Insert(TextileBindingModel model)
        {
            model.Id = source.Textils.Count > 0 ? source.Textils.Max(x => x.Id) + 1 : 1;
            var newTextile = Textile.Create(model);
            if (newTextile == null)
            {
                return null;
            }
            source.Textils.Add(newTextile);
            source.SaveTextils();
            return newTextile.GetViewModel;
        }

        public TextileViewModel? Update(TextileBindingModel model)
        {
            var textile = source.Textils.FirstOrDefault(x => x.Id == model.Id);
            if (textile == null)
            {
                return null;
            }
            textile.Update(model);
            source.SaveTextils();
            return textile.GetViewModel;
        }

        public TextileViewModel? Delete(TextileBindingModel model)
        {
            var element = source.Textils.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                source.Textils.Remove(element);
                source.SaveTextils();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
