// Required modules
const router = require('express').Router();
const util = require("./../utilities/utilities_main.js");
const jwt = require('jsonwebtoken');

router.post("/", async function(req, res) {
    try {
        const account = req.body.account;
        const password = req.body.password;
        // 
        let conn;
	    try {
	    	conn = await util.getDBConnection(); // get connection from db
	    	var result = await conn.query("SELECT * FROM user WHERE username = ? AND pass = ? ;", [account, password]);
            if (result.length == 1) {
                // valid user, create a token
                let is_assistant = result[0]['is_assistant'] == 1
                const data = {uid : account, is_assistant: is_assistant};
                const token = util.signJwtToken(data);
                if (!is_assistant){
                    var result = await conn.query("SELECT student_name FROM student WHERE student_id = ? ;", [account]);
                    var name = result[0]['student_name'];
                } else {
                    var result = await conn.query("SELECT assistant_name FROM assistant WHERE username = ? ;", [account]);
                    var name = result[0]['assistant_name'];
                }
                console.log(name);
                res.cookie("token", token);
                res.json({'suc' : true, 'is_assistant': is_assistant, 'name': name});
            }
            else {
                res.json({suc : false, msg : "wrong username or password"});
            }
	    }
	    catch(e) {
            console.error(e);
            res.json({suc : false});
	    }
	    finally {
		    util.closeDBConnection(conn); // close db connection
	    }
    }
    catch(e) {
        console.log(e);
    }
})

module.exports = router;
