using FishFactoryContracts.BindingModels;
using FishFactoryContracts.SearchModels;
using FishFactoryContracts.StoragesContracts;
using FishFactoryContracts.ViewModels;
using FishFactoryListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FishFactoryListImplement.Implements
{
	public class ImplementerStorage : IImplementerStorage
	{
		private readonly DataListSingleton _source;
		public ImplementerStorage()
		{
			_source = DataListSingleton.GetInstance();
		}
		public List<ImplementerViewModel> GetFullList()
		{
			var result = new List<ImplementerViewModel>();
			foreach (var Implement in _source.Implementers)
			{
				result.Add(Implement.GetViewModel);
			}
			return result;
		}
		public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel
	   model)
		{
			var result = new List<ImplementerViewModel>();
			if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password))
			{
				return result;
			}
			foreach (var Implement in _source.Implementers)
			{
				if (Implement.ImplementerFIO.Contains(model.ImplementerFIO))
				{
					result.Add(Implement.GetViewModel);
				}
			}
			return result;
		}
		public ImplementerViewModel? GetElement(ImplementerSearchModel model)
		{
			foreach (var Implement in _source.Implementers)
			{
				if ((string.IsNullOrEmpty(model.ImplementerFIO) || Implement.ImplementerFIO == model.ImplementerFIO) &&
								 (!model.Id.HasValue || Implement.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || Implement.Password == model.Password))
				{
					return Implement.GetViewModel;
				}
			}
			return null;
		}
		public ImplementerViewModel? Insert(ImplementerBindingModel model)
		{
			model.Id = 1;
			foreach (var Implement in _source.Implementers)
			{
				if (model.Id <= Implement.Id)
				{
					model.Id = Implement.Id + 1;
				}
			}
			var newImplement = Implementer.Create(model);
			if (newImplement == null)
			{
				return null;
			}
			_source.Implementers.Add(newImplement);
			return newImplement.GetViewModel;
		}
		public ImplementerViewModel? Update(ImplementerBindingModel model)
		{
			foreach (var Implement in _source.Implementers)
			{
				if (model.Id == Implement.Id)
				{
					Implement.Update(model);
					return Implement.GetViewModel;
				}
			}
			return null;
		}
		public ImplementerViewModel? Delete(ImplementerBindingModel model)
		{
			for (int i = 0; i < _source.Implementers.Count; ++i)
			{
				if (_source.Implementers[i].Id == model.Id)
				{
					var element = _source.Implementers[i];
					_source.Implementers.RemoveAt(i);
					return element.GetViewModel;
				}
			}
			return null;
		}
	}
}
