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

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

        private readonly ChildManager ChildManager = new ChildManager();

        // POST: api/Child/5
        [HttpPost("{id}")]
        public async Task<ActionResult<PublicChild>> GetPublicChild(int id, AuthGet get)
        {
            Session s = await Handler.GetSession(get.SessionID);
            if (s == null) return Unauthorized();

            try
            {
                return await ChildManager.GetChild(s, id);
            }
            catch (UnauthorizedAccessException)
            {
                return Unauthorized();
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
        }

        // PUT: api/Child/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutPublicChild(int id, PublicChild publicChild)
        {
            Session s = await Handler.GetSession(publicChild.SessionID);
            if (s == null) return Unauthorized();
            try {
                await ChildManager.UpdateChild(s, id, publicChild);
                return NoContent();
            }
            catch (UnauthorizedAccessException) {
                return Unauthorized();
            }
            catch (KeyNotFoundException) { 
                return NotFound();
            }
            catch (FormatException)
            {
                return BadRequest();
            }
        }

        // POST: api/Child
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<PublicChild>> PostPublicChild(PublicChild publicChild)
        {
            Session s = await Handler.GetSession(publicChild.SessionID);
            if (s == null ) return Unauthorized();

            try {
                int Id = await ChildManager.AddChild(s, publicChild);
                return CreatedAtAction("GetPublicChild", new { id = Id }, publicChild);
            }
            catch (UnauthorizedAccessException) {
                return Unauthorized();
            }
        }
    }
}