using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Enums;
using FishFactoryDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace FishFactoryDatabaseImplement.Models
{
	[DataContract]
	public class Order : IOrderModel
    {
		[DataMember]
		public int Id { get; private set; }
		[DataMember]
		[Required]
        public int ClientId { get; private set; }
		[DataMember]
		public int? ImplementerId { get; private set; }
		[DataMember]
		[Required]
		public int Count { get; private set; }
		[DataMember]
		[Required]
        public double Sum { get; private set; }
		[DataMember]
		[Required]
        public OrderStatus Status { get; private set; }
		[DataMember]
		[Required]
        public DateTime DateCreate { get; private set; } = DateTime.Now;
		[DataMember]
		public DateTime? DateImplement { get; private set; }
		[DataMember]
		[Required]
        public int CannedId { get; private set; }
		public virtual Canned Canned { get; set; }
		public virtual Client Client { get; set; }
		public virtual Implementer? Implementer { get; set; }
		public static Order? Create(OrderBindingModel model, FishFactoryDatabase context)
        {
            if (model == null)
            {
                return null;
            }
            return new Order()
            {
                Id = model.Id,
                ClientId = model.ClientId,
                Client = context.Clients.FirstOrDefault(x => x.Id == model.ClientId)!,
                ImplementerId = model.ImplementerId,
                Implementer = model.ImplementerId.HasValue ? context.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId) : null,
                Count = model.Count,
                Sum = model.Sum,
                Status = model.Status,
                DateCreate = model.DateCreate,
                CannedId = model.CannedId,
                Canned = context.Canneds.FirstOrDefault(x => x.Id == model.CannedId)!,
            };
        }

        public void Update(OrderBindingModel? model)
        {
            if (model == null)
            {
                return;
            }
            Status = model.Status;
            DateImplement = model.DateImplement;
            ImplementerId = model.ImplementerId;
        }

        public OrderViewModel GetViewModel => new()
        {
            CannedId = CannedId,
            CannedName = Canned.CannedName,
            ClientId = ClientId,
            ClientFIO = Client.ClientFIO,
            ImplementerId = ImplementerId,
			ImplementerFIO = Implementer?.ImplementerFIO,
			Count = Count,
            Sum = Sum,
            Status = Status,
            DateCreate = DateCreate,
            DateImplement = DateImplement,
            Id = Id,
        };
    }
}
