using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComputersShopFileImplement.Implements
{
    public class ComputerStorage : IComputerStorage
    {
        private readonly DataFileSingleton source;
        public ComputerStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public List<ComputerViewModel> GetFullList()
        {
            return source.Computers
            .Select(x => x.GetViewModel)
           .ToList();
        }

        public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComputerName))
            {
                return new();
            }
            return source.Computers.Where(x => x.ComputerName.Contains(model.ComputerName)).Select(x => x.GetViewModel).ToList();
        }

        public ComputerViewModel? GetElement(ComputerSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Computers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComputerName) && x.ComputerName == model.ComputerName) ||
            (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel;
        }

        public ComputerViewModel? Insert(ComputerBindingModel model)
        {
            model.Id = source.Computers.Count > 0 ? source.Computers.Max(x => x.Id) + 1 : 1;
            var newComputer = Computer.Create(model);
            if (newComputer == null)
            {
                return null;
            }
            source.Computers.Add(newComputer);
            source.SaveComputers();
            return newComputer.GetViewModel;
        }

        public ComputerViewModel? Update(ComputerBindingModel model)
        {
            var Computer = source.Computers.FirstOrDefault(x => x.Id == model.Id);
            if (Computer == null)
            {
                return null;
            }
            Computer.Update(model);
            source.SaveComputers();
            return Computer.GetViewModel;
        }
        public ComputerViewModel? Delete(ComputerBindingModel model)
        {
            var Computer = source.Computers.FirstOrDefault(x => x.Id == model.Id);
            if (Computer != null)
            {
                source.Computers.Remove(Computer);
                source.SaveComputers();
                return Computer.GetViewModel;
            }
            return null;
        }
    }
}
