using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlacksmithWorkshopDatabaseImplement.Models
{
    public class MessageInfo : IMessageInfoModel
    {
        [Key]
        public string MessageId { get; private set; } = string.Empty;
        public int? ClientId { get; private set; }
		[Required]
		public string SenderName { get; private set; } = string.Empty;
		[Required]
		public DateTime DateDelivery { get; private set; } = DateTime.Now;
		[Required]
		public string Subject { get; private set; } = string.Empty;
		[Required]
		public string Body { get; private set; } = string.Empty;
        public Client? Client { get; private set; }
		[Required]
		public bool IsReaded { get; set; }
		public string? ReplyMessageId { get; set; }
		[ForeignKey("ReplyMessageId")]
		public virtual MessageInfo? Reply { get; set; }
		[Required]
		public bool IsReply { get; set; }
		public static MessageInfo? Create(BlacksmithWorkshopDataBase context, MessageInfoBindingModel model)
        {
            if (model == null)
            {
                return null;
            }
            return new()
            {
                Body = model.Body,
                Subject = model.Subject,
                ClientId = context.Clients.FirstOrDefault(x => x.Email == model.SenderName)?.Id,
                Client = context.Clients.FirstOrDefault(x => x.Email == model.SenderName),
                MessageId = model.MessageId,
                SenderName = model.SenderName,
                DateDelivery = model.DateDelivery,
				IsReaded = model.IsReaded,
				ReplyMessageId = model.ReplyMessageId,
				IsReply = model.IsReply
			};
		}
		public void Update(BlacksmithWorkshopDataBase context, MessageInfoBindingModel model)
		{
			if (model == null)
			{
				return;
			}
			IsReaded = model.IsReaded;
			ReplyMessageId = model.ReplyMessageId;
			if (!string.IsNullOrEmpty(ReplyMessageId))
			{
				Reply = context.Messages.First(x => x.MessageId == ReplyMessageId);
			}
		}
		public MessageInfoViewModel GetViewModel => new()
        {
            Body = Body,
            Subject = Subject,
            ClientId = ClientId,
            MessageId = MessageId,
            SenderName = SenderName,
            DateDelivery = DateDelivery,
			IsReaded = IsReaded,
			ReplyMessageId = ReplyMessageId,
			Reply = Reply,
			IsReply = IsReply
		};
    }
}
