using SewingDressesContracts.BindingModels;
using SewingDressesContracts.SearchModels;
using SewingDressesContracts.StoragesContracts;
using SewingDressesContracts.ViewModels;
using SewingDressesListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SewingDressesListImplement.Implements
{
	public class ImplementStorage : IImplementStorage
	{
		private readonly DataListSingleton _source;
		public ImplementStorage()
		{
			_source = DataListSingleton.GetInstance();
		}
		public List<ImplementViewModel> GetFullList()
		{
			var result = new List<ImplementViewModel>();
			foreach (var Implement in _source.Implements)
			{
				result.Add(Implement.GetViewModel);
			}
			return result;
		}
		public List<ImplementViewModel> GetFilteredList(ImplementSearchModel
	   model)
		{
			var result = new List<ImplementViewModel>();
			if (string.IsNullOrEmpty(model.ImplementFIO) && string.IsNullOrEmpty(model.Password))
			{
				return result;
			}
			foreach (var Implement in _source.Implements)
			{
				if (Implement.ImplementFIO.Contains(model.ImplementFIO))
				{
					result.Add(Implement.GetViewModel);
				}
			}
			return result;
		}
		public ImplementViewModel? GetElement(ImplementSearchModel model)
		{
			foreach (var Implement in _source.Implements)
			{
				if ((string.IsNullOrEmpty(model.ImplementFIO) || Implement.ImplementFIO == model.ImplementFIO) &&
								 (!model.Id.HasValue || Implement.Id == model.Id) && (string.IsNullOrEmpty(model.Password) || Implement.Password == model.Password))
				{
					return Implement.GetViewModel;
				}
			}
			return null;
		}
		public ImplementViewModel? Insert(ImplementBindingModel model)
		{
			model.Id = 1;
			foreach (var Implement in _source.Implements)
			{
				if (model.Id <= Implement.Id)
				{
					model.Id = Implement.Id + 1;
				}
			}
			var newImplement = Implement.Create(model);
			if (newImplement == null)
			{
				return null;
			}
			_source.Implements.Add(newImplement);
			return newImplement.GetViewModel;
		}
		public ImplementViewModel? Update(ImplementBindingModel model)
		{
			foreach (var Implement in _source.Implements)
			{
				if (model.Id == Implement.Id)
				{
					Implement.Update(model);
					return Implement.GetViewModel;
				}
			}
			return null;
		}
		public ImplementViewModel? Delete(ImplementBindingModel model)
		{
			for (int i = 0; i < _source.Implements.Count; ++i)
			{
				if (_source.Implements[i].Id == model.Id)
				{
					var element = _source.Implements[i];
					_source.Implements.RemoveAt(i);
					return element.GetViewModel;
				}
			}
			return null;
		}
	}
}
