using BarContracts.BindingModels;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarDatabaseImplement.Models;

namespace BarDatabaseImplement.Implements
{
	public class MessageInfoStorage : IMessageInfoStorage
	{
		public List<MessageInfoViewModel> GetFullList()
		{
			using var Context = new BarDatabase();
			
			return Context.Messages
				.Select(x => x.GetViewModel)
				.ToList();
		}

		public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel Model)
		{
			using var Context = new BarDatabase();

			return Context.Messages
				.Where(x => x.ClientId.HasValue && x.ClientId ==  Model.ClientId)
				.Select(x => x.GetViewModel)
				.ToList();
		}

		public MessageInfoViewModel? GetElement(MessageInfoSearchModel Model)
		{
			if (string.IsNullOrEmpty(Model.MessageId))
				return null;

			using var Context = new BarDatabase();

			return Context.Messages
				.FirstOrDefault(x => x.MessageId == Model.MessageId)?
				.GetViewModel;
		}

		public MessageInfoViewModel? Insert(MessageInfoBindingModel Model)
		{
			var NewMessageInfo = MessageInfo.Create(Model);

			if (NewMessageInfo == null)
				return null;

			using var Context = new BarDatabase();
			Context.Messages.Add(NewMessageInfo);

			Context.SaveChanges();
			return NewMessageInfo.GetViewModel;
		}
	}
}
