using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrecastConcretePlantFileImplement.Implements
{
    public class ReinforcedStorage : IReinforcedStorage
    {
        private readonly DataFileSingleton source;

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

        public ReinforcedViewModel? Delete(ReinforcedBindingModel model)
        {
            var element = source.Reinforcedies.FirstOrDefault(x => x.Id == model.Id);

            if (element != null)
            {
                source.Reinforcedies.Remove(element);
                source.SaveReinforceds();

                return element.GetViewModel;
            }

            return null;
        }

        public ReinforcedViewModel? GetElement(ReinforcedSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ReinforcedName) && !model.Id.HasValue)
            {
                return null;
            }

            return source.Reinforcedies.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ReinforcedName) && x.ReinforcedName == model.ReinforcedName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public List<ReinforcedViewModel> GetFilteredList(ReinforcedSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ReinforcedName))
            {
                return new();
            }

            return source.Reinforcedies.Where(x => x.ReinforcedName.Contains(model.ReinforcedName)).Select(x => x.GetViewModel).ToList();
        }

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

        public ReinforcedViewModel? Insert(ReinforcedBindingModel model)
        {
            model.Id = source.Reinforcedies.Count > 0 ? source.Reinforcedies.Max(x => x.Id) + 1 : 1;
            var newReinforced = Reinforced.Create(model);

            if (newReinforced == null)
            {
                return null;
            }

            source.Reinforcedies.Add(newReinforced);
            source.SaveReinforceds();

            return newReinforced.GetViewModel;
        }

        public ReinforcedViewModel? Update(ReinforcedBindingModel model)
        {
            var reinforced = source.Reinforcedies.FirstOrDefault(x => x.Id == model.Id);

            if (reinforced == null)
            {
                return null;
            }

            reinforced.Update(model);
            source.SaveReinforceds();

            return reinforced.GetViewModel;
        }
    }
}
