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

namespace CoviDok.Data.MySQL
{
    public class ParentManager
    {
        private readonly IParentHandler handler = new MySqlParentHandler();
        public async Task<PublicParent> GetParent(int id)
        {
            Parent parent = await handler.GetParent(id);
            if (parent == null) throw new KeyNotFoundException();
            return parent.ToPublic();
        }

        public async Task UpdateParent(Session s, int id, PublicParent value)
        {
            if (id != value.Id) throw new FormatException();
            if (s.Id != id) throw new UnauthorizedAccessException();

            Parent parent = await handler.GetParent(id);
            if (parent == null) throw new KeyNotFoundException();

            parent.UpdateSelf(value);
            await handler.UpdateParent(id, parent);
        }

        public async Task<List<PublicChild>> GetChildren(int id)
        {
            if (!handler.ParentExists(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;
        }
    }
}