//---------------------------Einbinden von Modulen---------------------------


var url = require('url');
var fs = require('fs');
var mongo = require('mongodb');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);


//---------------------------Server Konfigurationen---------------------------

//Statische Seiten
app.use(express.static(__dirname + '/views'));

//Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//EJS Engine
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

//Verbindungsaufbau zur Datenbank
var MongoClient = mongo.MongoClient;
//URL der verbundenen Datenbank
var urlDB = "mongodb://localhost:27017/mydb";

//Session Management
app.use(session({secret: 'mySecret', saveUninitialized: true, resave: true}));
var sess;

//Starte Server
server.listen(8080);
console.log('server is listening on port 8080...');


//-----------------------------------Routen------------------------------------

//Überprüft ob Session vorliegt. Wenn ja -> feed. Wenn nein -> Login-Seite
app.get('/', function (req, res) {
    sess = req.session;
    if (sess.userName) {
        res.redirect('/feed');
    }
    else {
        res.render('logIn.html');
    }
});

//Verarbeitet Login-Daten
app.post('/logIn', function (req, res) {
    /*
        Überprüfen ob Daten in Datenbank liegen
        wenn ja:
     */

    var userName = req.body.name;
    var password = req.body.password;

    MongoClient.connect(urlDB, function(err, db) {
        if (err) throw err;
        console.log("Database connected");

        var query = { name: newUser };

        db.collection("customers").findOne(query, function(err, result) {
            if (err) throw err;
            if (isEmptyObject(result)) {
                sess = req.session;
                sess.userName = req.body.userName;
                res.end('done');
            }
            else {
                res.end('error');
            }
            db.close();
        });
    });
});

//Wenn User angemeldet ist -> rendert personalisierten feed. Wenn nicht angemeldet -> Login-Seite
app.get('/feed', function (req, res) {
    sess = req.session;

    if (sess.userName) {
        res.render('feed');
    }
    else {
        res.redirect('/');
    }
});

//Logout - Löscht Session und leitet zurück zur Login-Seite
app.get('/logOut', function (req, res) {
    req.session.destroy(function (err) {
        if (err) {
            console.log(err);
        }
        else {
            res.redirect('/');
        }
    });
});

//Verabeitet Registrierungsdaten
app.post('/register', function (req, res) {
    var userName = req.body.name;
    var password = req.body.password;
    var pictureId = req.body.pictureId;

    console.log("User: " + userName + ", Password: " + password);

    /*
    Ablegen der Daten in Datenbank
    */

        MongoClient.connect(urlDB, function(err, db) {
            if (err) throw err;
            console.log("Database connected");

            var newUser = userName;
            var newPassword = password;
            var newPictureId = pictureId;

            var myobj = { name: newUser, password: newPassword, pictureId: newPictureId };

            // Prüfung, ob der Username bereits vergeben ist

            var query = { name: newUser };

            db.collection("users").find(query).toArray(function(err, result) {
                if (err) throw err;
                if (result.length = 0) {
                    // Einfügen des neues Users, da Username nicht vergeben

                    db.collection("users").insertOne(myobj, function(err, res) {
                        if (err) throw err;
                        console.log("1 document inserted");
                    });
                    res.redirect('/');
                } else {
                    //Fehlermeldung: Username bereits vergeben
                    console.log("ERROR: Username bereits vergeben");
                    res.end('taken')
                }});

            db.close();
        });

});

//DATENBANKVERBINDUNG


/*MongoClient.connect(urlDB, function(err, db) {
  if (err) throw err;
  console.log("Database created!");

  //Registrierung neuer User

    var newUser;
    var newPassword;

    var myobj = { name: newUser, password: newPassword };

    //Userdaten in Datenbank einfügen
    db.collection("users").insertOne(myobj, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
    });

  //Loginverarbeitung

    var username;
    var password;

    var query = { name: username };

    db.collection("users").find(query).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);

        if (result.password == password) {
            //Login erfolgreich
        }
    });

  //Feed abrufen

    db.collection("beitraege").find({}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);

        //Feed ausgeben
    });

  //Feed filtern

  //Neuer Beitrag

  //Profilbild ändern

  //Biografie ändern

  db.close();
});*/

//SOCKET: BOT-POSTS

function botPost() {
    mongo.connect(urlDB, function (err, db) {
        if (err) throw err;
        var newPost = {/* Postdaten als JSON */}
        mongo.collection("posts").insertOne(myobj, function (err, res) {
            if (err) throw err;
            mongo.close();
        });
    });
};

io.on('connection', function (socket) {
    console.log('client connected on socket...');
    var rand = Math.round(Math.random() * (50000 - 500) + 500);

    setInterval(function () {
        //botPost();
        io.emit('newMessage');
        console.log('new Post...');
    }, rand);
});