/* Chromium Unity integration extension
 * 
 *   Copyright 2012 Canonical Ltd.
 *
 *   This program is free software: you can redistribute it and/or modify it 
 *   under the terms of the GNU General Public License version 3, as published 
 *   by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful, but 
 *   WITHOUT ANY WARRANTY; without even the implied warranties of 
 *   MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
 *   PURPOSE.  See the GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along 
 *   with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/

(function () {

// TODO extract based on logging settings
var log = {
    info: function(msg) {
        if (msg) {
            console.log('Info: ' + msg);
        }
    },
    error: function(msg) {
        if (msg) {
            console.log('Error: ' + msg);
        }
    }
};

log.info("Ubuntu web accounts extension loaded");

var plugin = document.getElementById('webaccountsChromiumExtensionId');
if (!plugin) {
    log.error("Unable to access NPAPI plugin");
    return;
}

function collect_cookies(msg) {
    var cookie_domain = msg.domain;
    if (cookie_domain[0] != ".") {
        cookie_domain = "." + cookie_domain;
    }
    var details = {
        domain: msg.domain
    }
    chrome.cookies.getAll(details, function(cookies) {
        var len = cookies.length;
        var cookie_strings = [];
        for (var i = 0; i < len; i++) {
            cookie_strings.push(cookies[i].name + "=" + cookies[i].value);
        }
        cookie_dict = {}
        cookie_dict[cookie_domain] = cookie_strings.join(";");
        plugin.setLoginInfo(JSON.stringify({
            login: msg.login,
            domain: msg.domain,
            cookies: cookie_dict
        }));
    });
}

function registerListener(webappsId) {
    chrome.extension.onRequestExternal.addListener(
            function(msg, sender, sendResponse) {
                log.info("Got webapps message");
                if (msg.type == "login") {
                    log.info("Login event; username = " + msg.login +
                        ", domain: " + msg.domain);

                    cookies = collect_cookies(msg);
                }
            });
    chrome.extension.sendRequest(webappsId,
        {action: "registerLoginListener"});
}

function isUnityWebApps(extension) {
    if (extension.name.indexOf("Unity WebApps") >= 0) {
        return true;
    } else {
        return false;
    }
}

chrome.management.onEnabled.addListener(function(info) {
    if (isUnityWebApps(info)) {
        log.info("WebApps extension enabled with id " + info.id);
        registerListener(info.id);
    }
});

chrome.management.getAll(function(result) {
    var webappsId = "";
    var len = result.length;
    for (var i = 0; i < len; i++) {
        log.info("Extension: " + result[i].name);
        if (isUnityWebApps(result[i])) {
            webappsId = result[i].id;
            break;
        }
    }

    if (webappsId) {
        log.info("WebApps extension found with id " + webappsId);
        registerListener(webappsId);
    } else {
        log.error("No WebApps extension found!");
    }
});

}) ();
