using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDatabaseImplement.Models;

namespace SoftwareInstallationDatabaseImplement
{
	public class MessageInfoStorage : IMessageInfoStorage
	{

		public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
		{
			using var context = new SoftwareInstallationDatabase();
			if (model.MessageId != null)
			{
				return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
			}
			return null;
		}

		public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
		{
			using var context = new SoftwareInstallationDatabase();
			var res = context.Messages
				.Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId)
				.Select(x => x.GetViewModel);
			if (!(model.Page.HasValue && model.PageSize.HasValue))
			{
				return res.ToList();
			}
			return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
		}

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

		public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
		{
			using var context = new SoftwareInstallationDatabase();
			var newMessage = MessageInfo.Create(model);
			if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId)))
			{
				return null;
			}
			context.Messages.Add(newMessage);
			context.SaveChanges();
			return newMessage.GetViewModel;
		}

        public MessageInfoViewModel? Update(MessageInfoBindingModel model)
        {
            using var context = new SoftwareInstallationDatabase();
            var res = context.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
            if (res != null)
            {
                res.Update(model);
                context.SaveChanges();
            }
            return res?.GetViewModel;
        }
    }
}
