using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoviDok.Api.Objects;
using CoviDok.Api.Request;
using CoviDok.BLL.Sessions;
using CoviDok.BLL.User.Managers;
using CoviDok.Data.MySQL;
using CoviDok.Data.SessionProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace CoviDok.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ParentController : ControllerBase
    {
        private readonly SessionHandler sessionHandler = new SessionHandler(new RedisProvider("redis"));

        private readonly ParentManager parentManager = new ParentManager();

        [HttpPost("{id}")]
        public async Task<ActionResult<PublicParent>> GetParent(int id, AuthGet get)
        {
            Session s = await sessionHandler.GetSession(get.SessionID);
            if (s == null) return Unauthorized();
            try {
                return await parentManager.GetParent(id);
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> PutParent(int id, PublicParent parent)
        {
            Session s = await sessionHandler.GetSession(parent.SessionID);
            if (s == null) return Unauthorized();
            try {
                await parentManager.UpdateParent(s, id, parent);
                return NoContent();
            }
            catch (UnauthorizedAccessException)
            {
                return Unauthorized();
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
            catch (FormatException)
            {
                return BadRequest();
            }
        }
        [HttpPost("{id}/children")]
        public async Task<ActionResult<List<PublicChild>>> GetChildrenOfParent(int id, AuthGet get)
        {
            Session s = await sessionHandler.GetSession(get.SessionID);
            if (s == null) return Unauthorized();
            try
            {
                return await parentManager.GetChildren(id);
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
            catch (UnauthorizedAccessException)
            {
                return Unauthorized();
            }
        }
    }
}