using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlacksmithWorkshopDatabaseImplement.Implements
{
    public class MessageInfoStorage : IMessageInfoStorage
    {
        public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
        {
            using var context = new BlacksmithWorkshopDataBase();
            if (!string.IsNullOrEmpty(model.MessageId))
            {
                return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
            }
            return null;
        }
		public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
		{
			if (model == null || !model.ClientId.HasValue && !model.PageLength.HasValue && !model.PageIndex.HasValue)
			{
				return new();
			}
			using var context = new BlacksmithWorkshopDataBase();
			if (model.PageLength.HasValue)
			{
				int skipRows = model.PageIndex.HasValue ? (model.PageIndex.Value - 1) * model.PageLength.Value : 0;
				return context.Messages
					.Where(x => !x.IsReply)
					.Where(x => !model.ClientId.HasValue || x.ClientId.HasValue && x.ClientId == model.ClientId)
					.OrderBy(x => x.DateDelivery)
					.Skip(skipRows)
					.Take(model.PageLength.Value)
					.Select(x => x.GetViewModel)
					.ToList();
			}
			return context.Messages
				.Where(x => !x.IsReply)
				.Where(x => !model.ClientId.HasValue || x.ClientId.HasValue && x.ClientId == model.ClientId)
				.OrderBy(x => x.DateDelivery)
				.Select(x => x.GetViewModel)
				.ToList();
		}
		public List<MessageInfoViewModel> GetFullList()
        {
            using var context = new BlacksmithWorkshopDataBase();
            return context.Messages
				.OrderBy(x => x.DateDelivery)
				.Select(x => x.GetViewModel)
                .ToList();
        }
		public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
		{
			using var context = new BlacksmithWorkshopDataBase();
			var newMessage = MessageInfo.Create(context, 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 BlacksmithWorkshopDataBase();
			var message = context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId);
			if (message == null)
			{
				return null;
			}
			message.Update(context, model);
			context.SaveChanges();
			return message.GetViewModel;
		}
	}
}
