package fr.eni.enchere.dal;

import fr.eni.enchere.bo.ForgotPassword;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Repository;

import java.security.SecureRandom;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

@Repository
@Primary
public class ForgotPasswordRepositoryImpl implements ForgotPasswordRepository {

    static final String keychain = "0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN";
    static SecureRandom randomValue = new SecureRandom();

    @Autowired
    private JavaMailSender javaMailSender;
    private final JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public ForgotPasswordRepositoryImpl(JavaMailSender javaMailSender, JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.javaMailSender = javaMailSender;
        this.jdbcTemplate = jdbcTemplate;
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    public class ForgotPasswordRowMapper implements RowMapper<ForgotPassword> {
        @Override
        public ForgotPassword mapRow(ResultSet rs, int rowNum) throws SQLException {
            ForgotPassword forgotPassword = new ForgotPassword();
            forgotPassword.setId(rs.getInt("id"));
            forgotPassword.setEmail(rs.getString("email"));
            forgotPassword.setLink(rs.getString("lien"));
            Calendar dateCreated = Calendar.getInstance();
            Calendar dateExpired = Calendar.getInstance();
            dateCreated.setTime(rs.getDate("dateCreate"));
            dateExpired.setTime(rs.getDate("dateExpire"));
            forgotPassword.setDateCreate(dateCreated);
            forgotPassword.setDateExpire(dateExpired);
            return forgotPassword;
        }
    }

    @Override
    public ForgotPassword getForgotPasswordByLink(String link) {
        String sql = "SELECT * FROM FORGOT WHERE lien = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new ForgotPasswordRepositoryImpl.ForgotPasswordRowMapper(), link);
        } catch (EmptyResultDataAccessException e) {
            // Aucun résultat trouvé, retourne null
            return null;
        }
    }

    @Override
    public void setForgotPasswords(String email) {
        String token = TokenGenreate();
        //Récupérer la date actuelle plus 10 minutes en plus
        Calendar dateNow = Calendar.getInstance();
        Calendar dateAgo = Calendar.getInstance();
        dateAgo.add(Calendar.MINUTE, 10);
        //Ajouter en base de donnée
        String sql = "INSERT INTO FORGOT (email, lien, dateCreate, dateExpire) VALUES (:email, :lien, :dateCreate, :dateExpire)";
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("email", email);
        parameters.addValue("lien", token);
        parameters.addValue("dateCreate", dateNow.getTime());
        parameters.addValue("dateExpire", dateAgo.getTime());
        namedParameterJdbcTemplate.update(sql, parameters);
        //Envoyer un email
        String link = "https://eni.enchere.horya.fr/forgotPassword?link=" + token;
        String linkLocal = "http://localhost:8800/forgotPassword?link=" + token;
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("support@horya.fr");
        message.setTo(email);
        message.setSubject("ENI Enchere - Demmande de changement de mot de passe");
        message.setText("Bonjour,\n\nVous avez demandé une réinitialisation de votre mot de passe. Veuillez utiliser le lien suivant pour procéder à la réinitialisation : " + link + "\nOU\n" + linkLocal);
        javaMailSender.send(message);
    }

    private String TokenGenreate(){
        //Déclaration de variable
        StringBuilder linkCreate = new StringBuilder(50);
        String sql = "SELECT * FROM FORGOT WHERE lien = ?";
        boolean isValide = false;
        //Traitement
        while (isValide == false){
            //Générer un code
            for (int i = 0; i < 50; i ++){
                linkCreate.append(keychain.charAt(randomValue.nextInt(keychain.length())));
            }
            //Vérifier existance dans la base de donnée
            try {
                jdbcTemplate.queryForObject(sql, new ForgotPasswordRepositoryImpl.ForgotPasswordRowMapper(), linkCreate.toString());
            } catch (EmptyResultDataAccessException e) {
                isValide = true;
            }
        }
        return linkCreate.toString();
    }
}
