var webPort = 8080;
var express = require('express');
const formidableMiddleware = require('express-formidable');
var app = express();
var ldapRTApi = require('./ldapRT.js');

const apiKeys = {
    "isertKey1Here": "standard",
    "isertKey2Here": "nicht vergeben",
    "isertKey3Here": "nicht vergeben",
}

app.use(formidableMiddleware());

var baseDirectory = '/web';

app.use(express.static(__dirname + baseDirectory));

const { spawn } = require('child_process');


const opsys = process.platform;

var ls = null;
if (opsys == "win32" || opsys == "win64") {
    ls = spawn('cmd');
} else {
    ls = spawn('/bin/bash');
}

var handeledMsgs = {};
var contactList = {};
var nextMembersToAdd = {};

ls.stdin.setEncoding('utf-8');

setTimeout(function () {
    if (opsys == "win32" || opsys == "win64") {
        ls.stdin.write("cd ./deltachat-core-rust && cargo run --example repl -- /home/dcdb && connect\n");
    } else {
        ls.stdin.write("source $HOME/.cargo/env && cd ./deltachat-core-rust && cargo run --example repl -- /home/dcdb && connect\n");
    }

}, 1000);

ls.stdout.on('data', data => {
    data = data.toString();

    if (data.indexOf("Delta Chat Core is awaiting your commands.") !== -1) {
        ls.stdin.write("connect\n");
    } else if (data.indexOf("Received") !== -1 && data.indexOf("Group#") === -1) {
        console.log(">>RESV", data);
        var spData = data.split("Received ");
        if (spData[1]) {
            var func = spData[1].split("(")[0].trim();
            console.log("function ---> ", func);
            // if (func == "INCOMING_MSG" || func == "DC_EVENT_MSGS_CHANGED") {
            //     var evalVar = data.split("Received ")[1].replace("}", "");
            //     try {
            //         eval(evalVar);
            //     } catch (e) {
            //         console.log("evalError", evalVar)
            //     }
            // }
        }
        //var chatId = data.split("INCOMING_MSG(")[1].split(",")[0];
        //ls.stdin.write("chat "+chatId+"\n");
        //ls.stdin.write("send BLUUB\n");
    } else if (data.indexOf("Contact#") !== -1) { //Contact listed
        var id = data.split(":")[0].split("#")[1];
        var spl = data.split("<");
        for (var i in spl) {
            var em = spl[i].split(">")[0];
            if (validateEmail(em)) {
                contactList[em] = id;
            }
        }
    } else if (data.indexOf("Group#") !== -1 && data.indexOf("created successfully") !== -1) { //GroupCreated
        var chatId = data.split("Group#")[1].split(" ")[0];
        console.log("Group is there... ->", chatId, nextMembersToAdd)
        ls.stdin.write("chat " + chatId + "\n");

        setTimeout(function () {
            var newMemberCnt = 0;
            for (var i in nextMembersToAdd) {
                newMemberCnt++;
                var UserId = contactList[nextMembersToAdd[i]];
                console.log("addmember " + UserId + "\n");
                ls.stdin.write("addmember " + UserId + "\n");
            }
            setTimeout(function () {
                ls.stdin.write("send Welcome to this brand new group!\rParticipants: "+newMemberCnt+"\rHave fun ヽ(•‿•)ノ\n");

                setTimeout(function () {
                    ls.stdin.write("removemember " + contactList["raphael@cloud13.de"] + "\n");
                    setTimeout(function () {
                        ls.stdin.write("delchat " + chatId + "\n");
                    }, 2000);
                }, 2000);
            }, 200);
        }, 100);

    } else {
        console.log(";;;", data);
    }

});

function INCOMING_MSG(chatId, msgId) { //Called on incoming messages
    handleIncomingMsgs(chatId, msgId)
}

function DC_EVENT_MSGS_CHANGED(chatId, msgId) { //Called on incoming messages and first contact
    handleIncomingMsgs(chatId, msgId)
}

function handleIncomingMsgs(chatId, msgId) {
    return;
    console.log("CHAT---_>", chatId, msgId);
    if (chatId > 0 || !chatsHandeled[msgId]) {
        handeledMsgs[msgId] = true;
        console.log("CHAT>>>>", chatId, msgId);

        ls.stdin.write("msginfo " + msgId + "\n");
        ls.stdin.write("markseen " + msgId + "\n");
        ls.stdin.write("chat " + chatId + "\n");
        ls.stdin.write("send Hello!\n");
    }
}

function createNewGroup(groupname, members) {
    for (var i in members) {
        ls.stdin.write("addcontact " + members[i] + "\n");
    }
    setTimeout(function () {
        ls.stdin.write("contacts\n");
        setTimeout(function () {
            nextMembersToAdd = members;
            ls.stdin.write("creategroup " + groupname + "\n");
        }, 500)
    }, 200)
}

ls.stderr.on('data', data => {
    console.log(`stderr: ${data}`);
});

ls.on('close', code => {
    console.log(`child process exited with code ${code}`);
});

app.post('/creategroup', function (req, res) {
    var apiKey = req.fields["apikey"] || "";
    var name = req.fields["groupname"] || "";
    var emails = req.fields["emails"] || "";
    var emailsSplit = emails.split(";");
    var vaildEmails = [];

    if (apiKeys[apiKey]) {
        for (var i in emailsSplit) {
            var em = emailsSplit[i].replace("\r", "").replace("\n", "").replace("\r", "").replace("\n", "").trim().toLowerCase();
            if (validateEmail(em)) {
                vaildEmails.push(em);
            }
        }
        if (name != "" && vaildEmails.length > 1) {
            createNewGroup(name, vaildEmails);
            console.log("Make group:", apiKey, name, vaildEmails);
            res.send('ok');
        } else {
            res.send('Groupname not vaild or no valid emails in list!');
        }
    } else {
        res.send('api key invaild! Code: 41!');
        console.log("Wrong api key was given!");
    }
});

app.post('/getLdapGroups', function (req, res) {
    var apiKey = req.fields["apikey"] || "";

    if (apiKeys[apiKey]) {
        console.log("GetLdapGroups:", apiKey);

        //Get all Erstsemestergruppen
        ldapRTApi.getAllFirstSemesterGroups("ldapUser", "LdapPw", function (err, content) { //Testaccount
            if (err) {
                return console.log(err);
            } else {
                console.log(content);
                res.send(JSON.stringify(content));
            }
        });
    } else {
        res.send('api key invaild! Code: 41!');
        console.log("Wrong api key was given!");
    }
});

app.listen(webPort, function () {
    console.log('App listening on port ' + webPort + '!');
});

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}