/* jshint esversion: 6 */

const config = require('../../config.js'),
        Slack = require('../slack.js').Slack,
        accountManager = require('../models/accounts.js').accountManager,
        accountConfigManager = require('../models/accountConfig.js').accountConfigManager;

module.exports.AccountController = {
    onRequest: function(req, res, srv) {
        if (req.urlObj.match(["account", "cguAccept"]) && req.method === "PUT") {
            req.account.dirty = true;
            req.account.cguReadAndAccepted = true;
            accountManager.save(req.account, () => {});
            res.writeHeader("204", "No Content");
            res.end();
        } else if (req.urlObj.urlParts[1] === "addservice") {
            switch (req.urlObj.urlParts[2]) {
                case "slack":
                    Slack.getOauthToken(req.urlObj.queryTokens.code, config.rootUrl +"account/addservice/slack", (teamName, teamId, token) => {
                        if (token) {
                            req.account.edit().addService("Slack", teamName, teamId, token);
                            accountManager.save(req.account);
                            accountConfigManager.defaultForAccount(req.account.id, (accConfig) => {
                                accConfig.edit().config.addService("Slack", teamName, teamId);
                                accountConfigManager.save(accConfig);
                            });
                        }
                        res.writeHeader("302", {
                            Location: config.rootUrl
                        });
                        res.end();
                    });
                break;

                default:
                    srv.execTemplate(require('../template/_404.js'), req, res);
                break;
            }
        } else {
            srv.execTemplate(require('../template/_404.js'), req, res);
        }
    }
};

