using RenovationWorkContracts.BindingModels;
using RenovationWorkContracts.SeatchModels;
using RenovationWorkContracts.StorageContracts;
using RenovationWorkContracts.ViewModels;
using RenovationWorkFileImplement.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RenovationWorkFileImplement.Implements
{
    public class RepairStorage : IRepairStorage
    {
        private readonly DataFileSingleton source;
        public RepairViewModel? Delete(RepairBindingModel model)
        {
            var document = source.Repairs.FirstOrDefault(x => x.Id == model.Id);
            if (document == null)
            {
                return null;
            }
            document.Update(model);
            source.SaveRepairs();
            return document.GetViewModel;
        }
        public RepairStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

        public RepairViewModel? GetElement(RepairSearchModel model)
        {
            if (string.IsNullOrEmpty(model.RepairName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Repairs
            .FirstOrDefault(x =>
                (!string.IsNullOrEmpty(model.RepairName) && x.RepairName == model.RepairName) ||
                (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;

        }

        public List<RepairViewModel> GetFilteredList(RepairSearchModel model)
        {
            if (string.IsNullOrEmpty(model.RepairName))
            {
                return new();
            }
            return source.Repairs
                .Where(x => x.RepairName.Contains(model.RepairName))
                .Select(x => x.GetViewModel)
                .ToList();

        }

        public List<RepairViewModel> GetFullList()
        {
                    return source.Repairs
            .Select(x => x.GetViewModel)
            .ToList();

        }

        public RepairViewModel? Insert(RepairBindingModel model)
        {
            model.Id = source.Repairs.Count > 0 ? source.Repairs.Max(x => x.Id) + 1 : 1;
            var newDoc = Repair.Create(model);
            if (newDoc == null)
            {
                return null;
            }
            source.Repairs.Add(newDoc);
            source.SaveRepairs();
            return newDoc.GetViewModel;
        }

        public RepairViewModel? Update(RepairBindingModel model)
        {
            var document = source.Repairs.FirstOrDefault(x => x.Id == model.Id);
			if (document == null)
			{
				return null;
			}
			document.Update(model);
			source.SaveRepairs();
			return document.GetViewModel;
        }
    }
}
