var express = require('express');
var router = express.Router();
const {Sequelize} = require("sequelize");
//___________________________________________________________________________________
// Ce petit script permet de connaitre la taille des services de kaz
//		-Nextcloud
//		-Postfix
//		-Agora
//!
// le script cherche dans la base mariaDB les differents données qui correspond à chaque
// services
//
// Auteur : Nathaniel Guiquerro Lauryne Gaultier
// Retourne : Une page serviceg.jade qui permet de afficher les tailles globales des 
// services kaz
// Exemple : Taille Postfix : 50 Mio
//	     Taille Nextcloud : 50 Mio
//	     Taille Agora : 10 Mio
//___________________________________________________________________________________
function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

router.get('/', function(req, res, next) {
    console.log("Demande de tailles aux scriptes de services");
    
    //__________________________________________________
    //
    //			Services Global de kaz 
    // concu de : Postfix, Nextcloud, Agora
    //
    //__________________________________________________

    // XXX Felix
    // const sequelize = new Sequelize("quotas","root","tartelette",{
    // 	host: "quotasDB",
    // 	dialect:"mariadb"
    // });
    
    (async ()=>{
  	try{
  	    await sequelize.authenticate();
  	    //connecté
  	    const query = "SELECT * FROM Global Order by date desc";
  	    sequelize.query(query).then(([results, metadata]) => {
         	var R = {"Agora: ":formatBytes(results[0].agora),
			 "Postfix: ":formatBytes(results[0].postfix),
			 "NextCloud: ":formatBytes(results[0].nextcloud),
			 "Total: ":formatBytes(results[0].total)};
		console.log(R);
		res.render('serviceg',{data:R});
	    })
  	} catch (error){
  	    //pas connecté
  	    console.log(error);
  	}
    })();
});

module.exports = router;
