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 MaterialStorage : IMaterialStorage
    {
        private readonly DataFileSingleton _source;

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

        public List<MaterialViewModel> GetFullList()
        {
            return _source.Components.Select(x => x.GetViewModel).ToList();
        }
        public List<MaterialViewModel> GetFilteredList(MaterialSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComponentName))
            {
                return new();
            }
            return _source.Components.Where(x => x.ComponentName.Equals(model.ComponentName)).Select(x => x.GetViewModel).ToList();
        }

        public MaterialViewModel? GetElement(MaterialSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComponentName) && !model.ID.HasValue)
            {
                return null;
            }

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

        public MaterialViewModel? Insert(MaterialBindingModel model)
        {
            model.ID = _source.Components.Count > 0 ? _source.Components.Max(x => x.ID) + 1 : 1;
            
            var newComponent = Material.Create(model);
            if (newComponent == null)
            {
                return null;
            }
            _source.Components.Add(newComponent);
            _source.SaveComponents();
            return newComponent.GetViewModel;
        }

        public MaterialViewModel? Update(MaterialBindingModel model)
        {
            var component = _source.Components.FirstOrDefault(x => x.ID == model.ID);
            if( component == null)
            {
                return null;
            }
            component.Update(model);
            _source.SaveComponents();
            return component.GetViewModel;
        }

        public MaterialViewModel? Delete(MaterialBindingModel model)
        {
            var component = _source.Components.FirstOrDefault(x => x.ID == model.ID);
            if(component == null)
            {
                return null;
            }
            _source.Components.Remove(component);
            _source.SaveComponents();
            return component.GetViewModel;;
        }
    }
}
