const express = require('express')
const mysql = require("mysql")
const dotenv = require('dotenv')
const app = express()
const path = require("path")
const publicDir = path.join(__dirname, './public')
const bcrypt = require("bcryptjs")
const bodyParser = require('body-parser')
const dateFormat = require('dateformat');


/* Connexion à la BDD MySQL */
dotenv.config({ path: './.env'})
const db = mysql.createConnection({
    host: process.env.DATABASE_HOST,
    port: process.env.DATABASE_PORT,
    user: process.env.DATABASE_USER,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE
})
db.connect((error) => {
    if(error) {
        console.log(error)
    } else {
        console.log("MySQL connected!")
    }
})

app.set('view engine', 'hbs');
app.use(express.static(publicDir));
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.json())


// *******************************************    Arrivée sur la page d'accueil    *******************************************
app.get("/", (req, res) => { 
    let today = dateFormat(new Date(), "yyyymmdd");

    // On récupère la liste des sessions actives
    db.query('SELECT ID, topic, DATE_FORMAT(scheduled_on, "%d/%m/%Y") as "date", DATE_FORMAT(scheduled_on, "%Hh%i") as "heure" FROM session WHERE DATE_FORMAT(scheduled_on, "%Y%m%d") >= ?', [today], async (error, result) => {
        if(error){
            console.log(error);
        }

        if (result.length == 0) {
            res.render("login-session", { error: 'Aucune session disponible' });
        }
        else {
            res.render("login-session", { select: result} );
        }
    })
 });

 app.get("/index", (req, res) => { res.render("index") });
 app.get("/login", (req, res) => { res.render("login") });
app.get("/register", (req, res) => {
    res.render("register", { session: req.query.s, role: req.query.r})
});


// *******************************************   Création d'un nouveau compte   *******************************************
app.post("/auth/register", (req, res) => {    
    const { gender, name, firstname, nickname, title, email, password, password_confirm, session, role } = req.body

    db.query('SELECT email FROM user WHERE email = ? OR nickname = ?', [email, nickname], async (error, result) => {
        if(error){
            console.log(error)
        }
        if( result.length > 0 ) {
            return res.render('register', {
                error: 'Adresse email ou pseudo déjà utilisé : modifiez votre saisie ou bien cliquez sur le lien ci-dessus pour vous connecter',
                session: session, role: role
            })
        } else if(password !== password_confirm) {
            return res.render('register', { 
                error: 'Vos mots de passe ne correspondent pas',
                session: session, role: role
            })
        }

        let hashedPassword = await bcrypt.hash(password, 8);
        db.query('INSERT INTO user SET?', {gender : (gender != undefined ? gender : ""), firstname: firstname, name: name, title: title, email: email, nickname : nickname, password: hashedPassword}, (err, result) => {
            if(error) {
                console.log(error)
            } else {
                return res.render('login', { session: session, role: role, email: email, nickname: nickname })
            }
        })  
    })
})

// *******************************************    Connexion sur le compte utilisateur    *******************************************
app.post("/auth/check-login", (req, res) => {    
    const { email, nickname, password, role, session } = req.body

    if (email == '' && nickname == '') {
        return res.render('login', {
            error: 'Veuillez saisir soit votre pseudo, soit une adresse email',
            "session": session,
            "role": role
        })
    }

    db.query('SELECT * FROM user WHERE email = ? OR nickname = ?', [email,nickname], async (error, result) => {
        if(error){
            console.log(error)
        }

        if( result.length == 0 ) {
            return res.render('login', {
                error: 'Utilisateur inconnu : veuillez créer votre compte via le lien ci-dessus',
                "session": session,
                "role": role
            })
        }

        var userId = result[0].ID
        bcrypt.compare(password, result[0].password, function(err, result) {
            if(result) {

                // Le user est connecté avec succès : on vérifie qu'il n'est pas déjà inscrit à la session et si pas le cas, on l'inscrit et on incrémente le compteur des participants
                db.query('SELECT * FROM participation WHERE user = ?', [userId], async (error, result) => {
                    if(error) {
                        console.log(error)
                    }

                    if (result.length == 0) {
                        db.query('INSERT INTO participation (user, session, role_during_session) VALUES (?,?,?)', [userId, session[0], role[0]], function (err, result) {
                            if (err) throw err;
                            console.log("1 record inserted");
                          });

                        db.query('UPDATE session SET nb_of_participants = nb_of_participants + 1 WHERE ID=?', session, function (err, result) {
                            if (err) throw err;
                            console.log("1 record updated");
                          });
                    }
                })

                if (role == 'A') {
                    res.redirect('https://mia.thecoredev.fr');
                }
                else {
                    res.redirect('https://mia.thecoredev.fr');
                }
            }
            else {
                return res.render('login', {
                    error: 'Mot de passe incorrect : corriger votre saisie',
                    "session": session,
                    "role": role
                })
            }
        })
    })
})


// *******************************************    Connexion sur la session    *******************************************
app.post("/auth/check-session", (req, res) => { 
    
    const { session, session_password, role } = req.body
    let listeSessions;

    let today = dateFormat(new Date(), "yyyymmdd");
    db.query('SELECT ID, topic, DATE_FORMAT(scheduled_on, "%d/%m/%Y") as "date", DATE_FORMAT(scheduled_on, "%Hh%i") as "heure" FROM session WHERE DATE_FORMAT(scheduled_on, "%Y%m%d") >= ?', [today], async (error, result) => {
        if(error){
            console.log(error);
        }
        if (result.length == 0) {
            res.redirect('');
        }
        else {
            listeSessions = result;
        }
    });

    db.query('SELECT password, topic, DATE_FORMAT(scheduled_on, "%d/%m/%Y %H:%i") as "date" FROM session WHERE ID = ?', [session], async (error, result) => {
        if(error){
            console.log(error)
        }
        if( result.length == 0 ) {
            return res.render('login-session', {
                error: 'Session inconnue : veuillez saisir un identifiant de session valide'
            })
        }
        else {
            if (result[0].password === session_password) {
                return res.render('login', {"session": session, "role": role, "topic": result[0].topic, "session_date": result[0].date})
            }
            else {
                return res.render('login-session', {
                    "error": "Mot de passe incorrect : corriger votre saisie",
                    "select": listeSessions
                })
            }
        }
    })
})


app.listen(5005, ()=> {
    console.log("server started on port 5005")
})