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

namespace FishFactoryDatabaseImplement.Implements
{
	public class MessageInfoStorage : IMessageInfoStorage
	{
		public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
		{
			if (string.IsNullOrEmpty(model.MessageId))
			{
				return null;
			}
			using var context = new FishFactoryDatabase();
			return context.Messages.Include(x => x.Client).FirstOrDefault(x => x.MessageId.Equals(model.MessageId))?.GetViewModel;
		}

		public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
		{
			if (!model.ClientId.HasValue)
			{
				return new();
			}
			using var context = new FishFactoryDatabase();
			return context.Messages.Include(x => x.Client).Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList();
		}

		public List<MessageInfoViewModel> GetFullList()
		{
			using var context = new FishFactoryDatabase();
			return context.Messages.Include(x => x.Client).Select(x => x.GetViewModel).ToList();
		}


		public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
		{
			using var context = new FishFactoryDatabase();
			model.ClientId = context.Clients.FirstOrDefault(x => x.Email.Equals(model.SenderName))?.Id;
			var message = MessageInfo.Create(model);
			if (message == null)
				return null;
			context.Messages.Add(message);
			try
			{
				context.SaveChanges();
				return message.GetViewModel;
			}
			catch (Exception ex)
			{
				return null;
			}
		}
	}
}
