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

namespace ComputersShopListImplement.Implements
{
	public class ComputerStorage : IComputerStorage
	{
		private readonly DataListSingleton _source;
		public ComputerStorage()
		{
			_source = DataListSingleton.GetInstance();
		}
		public List<ComputerViewModel> GetFullList()
		{
			var result = new List<ComputerViewModel>();
			foreach (var Computer in _source.Computers)
			{
				result.Add(Computer.GetViewModel);
			}
			return result;
		}
		public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
		{
			var result = new List<ComputerViewModel>();
			if (string.IsNullOrEmpty(model.ComputerName))
			{
				return result;
			}
			foreach (var Computer in _source.Computers)
			{
				if (Computer.ComputerName.Contains(model.ComputerName))
				{
					result.Add(Computer.GetViewModel);
				}
			}
			return result;
		}
		public ComputerViewModel? GetElement(ComputerSearchModel model)
		{
			if (string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
			{
				return null;
			}
			foreach (var Computer in _source.Computers)
			{
				if ((!string.IsNullOrEmpty(model.ComputerName) && Computer.ComputerName == model.ComputerName) ||
				(model.Id.HasValue && Computer.Id == model.Id))
				{
					return Computer.GetViewModel;
				}
			}
			return null;
		}
		public ComputerViewModel? Insert(ComputerBindingModel model)
		{
			model.Id = 1;
			foreach (var Computer in _source.Computers)
			{
				if (model.Id <= Computer.Id)
				{
					model.Id = Computer.Id + 1;
				}
			}
			var newComputer = Computer.Create(model);
			if (newComputer == null)
			{
				return null;
			}
			_source.Computers.Add(newComputer);
			return newComputer.GetViewModel;
		}
		public ComputerViewModel? Update(ComputerBindingModel model)
		{
			foreach (var Computer in _source.Computers)
			{
				if (Computer.Id == model.Id)
				{
					Computer.Update(model);
					return Computer.GetViewModel;
				}
			}
			return null;
		}
		public ComputerViewModel? Delete(ComputerBindingModel model)
		{
			for (int i = 0; i < _source.Computers.Count; ++i)
			{
				if (_source.Computers[i].Id == model.Id)
				{
					var element = _source.Computers[i];
					_source.Computers.RemoveAt(i);
					return element.GetViewModel;
				}
			}
			return null;
		}
	}
}
