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

namespace CoviDok.Data.MySQL
{
    public class DoctorManager
    {
        private readonly IDoctorHandler handler = new MySqlDoctorHandler();
        public async Task<List<PublicDoctor>> GetDoctors()
        {
            
            List<PublicDoctor> ret = new List<PublicDoctor>();
            await Task.Run( () => {
                var docs = handler.GetDoctors();
                foreach (Doctor doctor in docs)
                {
                    ret.Add(doctor.ToPublic());
                }
            });           
            return ret;
        }

        public async Task<PublicDoctor> GetDoctor(int id)
        {
            Doctor doc = await handler.GetDoctor(id);
            if (doc == null) throw new KeyNotFoundException();
            return doc.ToPublic();
        }

        public async Task UpdateDoctor(Session s, int id, PublicDoctor value)
        {
            if (id != value.ID) throw new FormatException();
            if (s.ID != id) throw new UnauthorizedAccessException();

            Doctor doc = await handler.GetDoctor(id);
            if (doc == null) throw new KeyNotFoundException();

            doc.UpdateSelf(value);
            await handler.UpdateDoctor(id, doc);
        }

        public async Task<List<PublicAssistant>> GetAssistants(int id)
        {
            if (!handler.DoctorExists(id)) throw new KeyNotFoundException();
            List<PublicAssistant> ret = new List<PublicAssistant>();
            await Task.Run(() => {
                var asts = handler.GetAssistants(id);
                foreach (Assistant assistant in asts)
                {
                    ret.Add(assistant.ToPublic());
                }
            });
            return ret;
        }

        public async Task<List<PublicChild>> GetChildren(int id)
        {
            if (!handler.DoctorExists(id)) throw new KeyNotFoundException();
            List<PublicChild> ret = new List<PublicChild>();
            await Task.Run(() => {
                var asts = handler.GetChildren(id);
                foreach (Child child in asts)
                {
                    ret.Add(child.ToPublic());
                }
            });
            return ret;
        }
    }
}