using Microsoft.EntityFrameworkCore;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;

namespace SecuritySystemDatabaseImplement.Implements
{
    public class MessageInfoStorage : IMessageInfoStorage
    {
        public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
        {
            return GetFilteredList(model).FirstOrDefault();
        }

        public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
        {
            var messageInfos = GetFullList();
            if (!string.IsNullOrEmpty(model.MessageId))
            {
                messageInfos = messageInfos.Where(x => x.MessageId == model.MessageId).ToList();
            }
            if (model.ClientId != null)
            {
                messageInfos = messageInfos.Where(x => x.ClientId == model.ClientId).ToList();
            }
            return messageInfos;
        }

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

        public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
        {
            var messageInfo = MessageInfo.Create(model);
            if (messageInfo == null)
            {
                return null;
            }
            using var context = new SecuritySystemDatabase();
            context.MessageInfos.Add(messageInfo);
            context.SaveChanges();
            return messageInfo.GetViewModel;
        }
    }
}
