using Dto.Classe;
using Dto.Factories;
using Interface;
using Microsoft.AspNetCore.Mvc;
using Modele.Classe;
using System.Runtime.Intrinsics.X86;

namespace Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class Ecuries : Controller
    {
        private readonly IApi data;

        public Ecuries(IApi manager)
        {
            this.data = manager;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            try
            {
                var ecuries = await data.GetEcuries();
                if (ecuries == null)
                {
                    return NotFound();
                }
                else
                {
                    return Ok(ecuries.Select(e => e.ModeleToDTO()));
                }
            } catch(Exception e) {
                return BadRequest(e.Message);
            }
        }


        [HttpGet("{name}")]
        public async Task<IActionResult> Get(string name)
        {

            Ecurie ecurie = await data.GetOneEcurie(name);
            if (ecurie == null)
            {
                return NotFound(name);
            }
            else
            {
                return Ok(ecurie.ModeleToDTO());
            }
        }

        [HttpPost]
        public async Task<IActionResult> Post(EcurieDTO ecurie,string pseudo)
        {

            List<int> result = new List<int>();
            result = await data.AddEcurie(ecurie.DTOToModele(),pseudo);

            if (result.ToList()[0] == 1)
            {
                int tmpListe = result.ToList()[1];
                if (tmpListe == 2)
                {
                    return BadRequest("Le nom de l'écurie est déjà pris !");
                }
                else if (tmpListe == 3)
                {
                    return BadRequest("Le pilote n'existe pas !");
                }
                else if (tmpListe == 4)
                {
                    return BadRequest("Le pilote fait déjà partie d'une écurie !");
                }
                else
                {
                    return BadRequest("Erreur !");
                }
            }
            return CreatedAtAction(nameof(Get), new { name = ecurie.Name }, ecurie);
        }
    }
}
