
import mysql from "mysql2/promise";

import {
    getConfig
} from "./config.mjs";

const configData = await getConfig();

var connection = null;
await connect();

export async function connect(params) {
    if (connection != null) {
        connection.destroy();
    }

    // Create the connection to database
    connection = await mysql.createConnection({
        host: configData.database.host,
        port: configData.database.port,
        database: configData.database.database,
        user: configData.database.username,
        password: configData.database.password
    });

    await connection.connect();

    connection.on('connection', async () => {
        console.log("database connection successful!");
    });

    connection.on('error', async (mysqlError) => {
        if (mysqlError.code == "PROTOCOL_CONNECTION_LOST") {
            console.log("database connection lost. reconnecting...");
            await connect();
        }
    });
}

export async function login(username, password) {
    try {
        const [rows] = await connection.execute('SELECT id, uidnumber, name, otpsecret FROM `users` WHERE `name` = ? AND `passsha256` = ? AND `disabled` = 0', [username, password]);

        if (rows.length == 0) {
            throw new Error(`user ${username} not found.`);
        }
        if (rows.length > 1) {
            throw new Error("more than 1 user found.");
        }

        console.log(`user ${rows[0].name} logged in.`);
        return rows[0];
    } catch (error) {
        console.log(`login failed: ${error.message}`);
        return null;
    }
}

export async function getUser(userid) {
    try {
        const [rows] = await connection.execute('SELECT uidnumber, name, givenname, sn, mail, custattr FROM `users` WHERE `id` = ?', [userid]);

        if (rows.length == 0) {
            throw new Error("no user found.");
        }

        return rows[0];
    } catch (error) {
        return null;
    }
}

export async function getUserMFA(userid) {
    try {
        const [rows] = await connection.execute('SELECT otpsecret, yubikey FROM `users` WHERE `id` = ?', [userid]);

        if (rows.length == 0) {
            throw new Error("no user found.");
        }

        return rows[0];
    } catch (error) {
        return null;
    }
}

export async function setOTPSecret(userid, otpsecret) {
    try {
        await connection.execute('UPDATE `users` SET `otpsecret` = ? WHERE `id` = ?', [otpsecret, userid]);
        return true;
    } catch (error) {
        return false;
    }
}



export async function getUsers() {
    let [mysqlUsers] = await connection.execute('SELECT id, name, uidnumber, mail, disabled FROM `users`', []);
    return mysqlUsers;
}

export async function getGroups() {
    let [mysqlGroups] = await connection.execute('SELECT * FROM `ldapgroups`', []);
    return mysqlGroups;
}

export async function getUserGroups(userid) {
    try {
        let [mysqlUsers] = await connection.execute('SELECT primarygroup, othergroups FROM `users` WHERE `id` = ?', [userid]);
        let [mysqlGroups] = await connection.execute('SELECT * FROM `ldapgroups`', []);

        mysqlGroups = mysqlGroups.map((mysqlGroup) => {
            return {
                id: mysqlGroup.id,
                name: mysqlGroup.name
            }
        });

        let result = [];

        if (mysqlUsers[0].primarygroup != '') {
            
        }

        return true;
    } catch (error) {
        return false;
    }
}
