using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.ViewModels;
using CaseAccountingDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CaseAccountingDataBaseImplement.Models
{
    public class Hearing : IHearingModel
    {
        public int Id { get; set; }

        [Required]
        public string Information { get; set; } = string.Empty;

        [Required]
        public DateTime Date { get; set; }

        [Required]
        public int CaseId { get; set; }
        public virtual Case Case { get; set; } = new();

        [Required]
        public int UserId { get; set; }
        public virtual User User { get; set; } = new();

        public static Hearing? Create (CaseAccountingDatabase context, HearingBindingModel? model)
        {
            if (model == null)
            {
                return null;
            }
            return new Hearing()
            {
                Id = model.Id,
                Information = model.Information,
                Date = model.Date,
                CaseId = model.CaseId,
                Case = context.Cases.FirstOrDefault(x => x.Id == model.CaseId) ?? throw new Exception("Case не существует"),
                UserId = model.UserId,
                User = context.Users.FirstOrDefault(x => x.Id == model.UserId) ?? throw new Exception("User не существует")
            };
        }

        public void Update (CaseAccountingDatabase context, HearingBindingModel? model)
        {
            if (model == null)
            {
                return;
            }
            Information = model.Information;
            CaseId = model.CaseId;
            Case = context.Cases.FirstOrDefault(x => x.Id == model.CaseId) ?? throw new Exception("Case не существует");
            DateTime.SpecifyKind(model.Date, DateTimeKind.Utc);
        }

        public HearingViewModel GetViewModel => new()
        {
            Id = Id,
            Information = Information,
            Date = Date,
            CaseId = CaseId,
            UserId = UserId
        };
    }
}
