using Dto.Classe;
using Dto.Factories;
using Entity_Framework;
using Entity_Framework.Entity;
using Entity_Framework.Factories;
using Modele.Classe;
using System.Security.Cryptography;
using System.Text;

namespace Extraction_Donnees.Extraction
{
    public partial class Extraction
    {
        public Task<IEnumerable<Pilote>> GetPilotes()
        {
            IEnumerable<Pilote> result = new List<Pilote>();

            using (BDDContext db = new BDDContext())
            {
                result = db.Pilotes.ToList().Select(e => e.EntityToModele());
            }
            return Task.FromResult(result);
        } 

        public Task<Pilote> GetOnePilote(string pseudo)
        {
            Pilotes pilote = new Pilotes();

            using (BDDContext db = new BDDContext())
            {
                pilote = db.Pilotes.Where( e => e.Pseudo == pseudo).FirstOrDefault();
            }
            if (pilote == null)
            {
                return Task.FromResult<Pilote>(null);
            }
            return Task.FromResult<Pilote>(pilote.EntityToModele());
        }

        public Task<Pilote> AddPilote(Pilote pilote)
        {
            Pilotes piloteEntity = pilote.ModeleToEntity();

            using (BDDContext db = new BDDContext())
            {
                IEnumerable<Pilotes> piloteCheck = db.Pilotes.Where(e => e.Pseudo == piloteEntity.Pseudo );
                if (piloteCheck.Count() != 0)
                {
                    return Task.FromResult<Pilote>(null);
                }
                db.Add(piloteEntity);
                db.SaveChanges();
            }

            return Task.FromResult<Pilote>(pilote);
        }

        public Task<Pilote> CheckPilote(string Email, string password)
        {
            byte[] passwordByte = Encoding.UTF8.GetBytes(password);
            SHA256 sha256 = SHA256.Create();
            byte[] hashedByte = sha256.ComputeHash(passwordByte);
            string hashedPassword = Convert.ToBase64String(hashedByte);

            using (BDDContext db = new BDDContext())
            {
                Pilotes pilote =  db.Pilotes.Where(e => e.Email == Email && e.Password == hashedPassword).FirstOrDefault();
                if (pilote == null)
                {
                    return Task.FromResult<Pilote>(null);
                }
                return Task.FromResult(pilote.EntityToModele());
            }
        }
    }
}
