var express = require("express");
var cookieParser = require("cookie-parser");
var path = require("path");
var errorHandler = require("errorhandler");
var app = express();

app.use(cookieParser());
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    return next();
});
app.use(express.static(path.join(process.cwd(), "StaticPages")));
app.use(errorHandler({ dumpExceptions: true, showStack: true }));

var uuid = require("uuid/v4");
var mysql = require("mysql");
var fs = require("fs");
var cause;

var con = mysql.createConnection({
    host: "localhost",
    user: "minis",
    password: "Wnc4q_75",
    database: "minis"
});

con.connect(err => {
    if (err) {
        console.log("Cant connect to MySQL database");
        console.log(err);
        cause = err;
    }
    console.log("Connected to database!");
});


app.get('/', (req, res) => {
    res.send("Welcome to the miniplan api!");
});

app.get('/login', (req, res) => {
    var username = req.query.username;
    var password = req.query.password;

    if(username == undefined || password == undefined){
        res.send({success: false, error: "Missing parameters"});
        return;
    }

    username = username.toLowerCase();

    /*con.query("SELECT UserToken FROM ministranten WHERE Username='" + username + "'", (err, result) => {
        if(result[0]["UserToken"] == req.cookies.loginToken){
            res.send({success: true});
        }else{*/
            con.query("SELECT Passwort FROM ministranten WHERE Username='" + username + "'", (err, result) => {
                if (err) throw err;
                if(password == result[0]["Passwort"]){
                    var usertoken = uuid();
                    res.cookie("loginToken", usertoken);
                    res.cookie("user", username);
                    con.query("UPDATE `ministranten` SET `UserToken` = '" + usertoken + "' WHERE `ministranten`.`Username` = '" + username + "';");
                    res.send({success: true, token: usertoken});
                }else{
                    res.send({success: false});
                }
            });
        /*}
    });*/
});

app.get("/logout", (req, res) => {
    var token = req.cookies.loginToken;
    var user = req.cookies.user;

    con.query("SELECT UserToken FROM ministranten WEHER Username='" + username + "'", (err, result) => {
        if (err) throw err;

        if(result[0]["UserToken"] == token){
            con.query("UPDATE `ministranten` SET `UserToken` = '' WHERE `ministranten`.`Username` = '" + user + "';");
            res.cookie("loginToken", "");
            res.cookie("user", "");
            res.send({success: true});
        }else{
            res.send({success: false});
        }
    });


});

app.get("/user/:user/update", (req, res) => {
});


app.get("/gottesdienste", (req, res) => {
    var groupid = req.params.groupid;
    con.query("SELECT ID from gottesdienstgruppe ORDER BY ID DESC LIMIT 1", (err, result) => {
        if (err) throw err;
        con.query("SELECT * from gottesdienste WHERE GruppeID='" + result[0]["ID"] + "' ORDER BY `gottesdienste`.`Datum` ASC LIMIT 0 , 30 ", (err, result) => {
            if (err) throw err;
            res.send(JSON.stringify(result));
        });
    });

});

app.get("/gottesdienste/:groupid", (req, res) => {
    var groupid = req.params.groupid;
    con.query("SELECT * from gottesdienste WHERE GruppeID='" + groupid + "' ORDER BY  `gottesdienste`.`Datum` ASC LIMIT 0 , 30", (err, result) => {
        if (err) throw err;
        res.send(JSON.stringify(result));
    });
});

app.get("/groups", (req, res) => {
    con.query("SELECT * from gottesdienstgruppe ORDER BY  `gottesdienstgruppe`.`ID` DESC  LIMIT 0, 5", (err, result) => {
        if (err) throw err;
        res.send(JSON.stringify(result));
    });
});

app.get("/ministranten", (req, res) =>{
    con.query("SELECT UserToken FROM ministranten WHERE UserToken='" + req.cookies.loginToken + "'", (err, result) => {
        var loggedIn = result.length == 1;
        con.query("SELECT Name, Username FROM `ministranten`", (err, result) => {
            if (err) throw err;
            var minis = result;
            
            var finished = 0;
            
            minis.splice(0, 1);
            for(var i = 0; i < minis.length; i++){
                attachToMini(minis[i], i, (mini, pos) => {
                    minis[pos] = mini;
                    finished++;
                    if(finished == minis.length){
                        if(!loggedIn){
                            for(var i = 0; i < minis.length; i++){
                                if(minis[i]["Name"] == "admin"){
                                    minis.splice(0, 1);
                                    i--;
                                    continue;
                                }
                                minis[i]["Name"] = minis[i]["Name"].split(" ")[0].substring(0, 1) + ". " + minis[i]["Name"].split(" ")[1];
                            }
                        }
                        res.send(JSON.stringify(minis));
                    }
                });
            }
            

        });
    });
});

var attachToMini = function(mini, pos, then){
    mini.registered = [];
    con.query("SELECT * FROM `" + mini.Name.toLowerCase() + "` LIMIT 0 , 30", (err, data) => {
        if(data == null){
            then(mini, pos);
        }
        for(var j = 0; j < data.length; j++){
            
            mini.registered[j] = {
                id: data[j]["GottesdienstIDs"],
                value: data[j]["Anwesend"]
            };
        }
        then(mini, pos);
    });
}


app.listen(process.env.PORT);
console.log("Starting api-server on " + process.env.PORT);






function isConnected(){
    if(con.isConnected){
        return true;
    }else{
        return false;
    }
}


function removeFromArrayByValue(value, array) {
    var index = array.indexOf(value);
    if(index > -1){
        array.splice(index, 1);
    }
}

function removeFromArray(index, array) {
    var index = array.indexOf(value);
    if(index > -1){
        array.splice(index, 1);
    }
}