using CoviDok.Api.Objects;
using CoviDok.BLL.Sessions;
using CoviDok.BLL.User.Managers;
using CoviDok.Data.Model;
using CoviDok.Data.MySQL;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoviDok.Data.MySQL
{
    public class ChildManager
    {
        private readonly IChildHandler handler = new MySqlChildHandler();
        public async Task<PublicChild> GetChild(Session s, int id)
        {
            Child child = await handler.GetChild(id);
            if (child == null) throw new KeyNotFoundException();
            if (child.DoctorId == s.ID || child.ParentId == s.ID)
            {
                return child.ToPublic();
            }
            else {
                throw new UnauthorizedAccessException();
            }
        }
        
        public async Task UpdateChild(Session s, int id, PublicChild newData)
        {
            if (id != newData.ID) throw new FormatException();

            Child child = await handler.GetChild(id);
            if (child == null) throw new KeyNotFoundException();
            if (child.ParentId == s.ID || child.DoctorId == s.ID)
            {
                child.UpdateSelf(newData);
                await handler.UpdateChild(id, child);
            }
            else
            {
                throw new UnauthorizedAccessException();
            }
        }

        public async Task<int> AddChild(Session s, PublicChild newChild)
        {
            if (s.ID != newChild.ParentId) throw new UnauthorizedAccessException();
            Child child = new Child();
            child.UpdateSelf(newChild);
            child.RegistrationDate = DateTime.Now;
            return await handler.AddChild(child);
        }
    }
}