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 DeltaChat = require('deltachat-node')
const dc = new DeltaChat()

const opts = {
    addr: 'add',
    mail_pw: 'pw'
}

dc.on('ALL', console.log.bind(null, 'core |'))

dc.on('DC_EVENT_INCOMING_MSG', (chatId, msgId) => {
    const msg = dc.getMessage(msgId)
    console.log(chatId, msg)
    dc.sendMessage(chatId, `Bot agrees to ${Math.random() * 100}%`)
})

dc.open(() => {
    const onReady = () => {
        console.log("DeltaChat Core is ready!");
    }
    if (!dc.isConfigured()) {
        dc.once('ready', onReady)
        dc.configure(opts)
    } else {
        onReady()
    }
})

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

    if (apiKeys[apiKey]) {
        if (dc.isOpen()) { //Check if deltaChat is running
            for (var i in emailsSplit) {
                var em = emailsSplit[i].replace("\r", "").replace("\n", "").replace("\r", "").replace("\n", "").trim().toLowerCase();
                if (validateEmail(em) && DeltaChat.maybeValidAddr(em)) {
                    vaildEmails.push(em);
                }
            }
            if (groupname != "" && vaildEmails.length > 1) {
                var groupChatId = dc.createUnverifiedGroupChat(groupname)
                for (var i in vaildEmails) {
                    var name = vaildEmails[i].split("@")[0];
                    var addr = vaildEmails[i];
                    var contactId = dc.createContact(name, addr);
                    console.log(groupChatId, contactId);
                    dc.addContactToChat(groupChatId, contactId)
                }
                setTimeout(function () {
                    dc.sendMessage(groupChatId, "Welcome to this brand new group!\rParticipants: " + vaildEmails.length + "\rHave fun ヽ(•‿•)ノ")
                    setTimeout(function () {
                        dc.removeContactFromChat(groupChatId, 1);
                    }, 1000);
                }, 1000)
                //createNewGroup(name, vaildEmails);
                console.log("Make group:", apiKey, groupname, 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", "password", 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());
}