// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
var Cu = Components.utils;
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;

Cu.import("resource://unity/unity-webapps.js");
Cu.import("resource://unity/l10n.js");

var ExceptionsManager = {
    uwa: new UnityWebapps(),
    domains: {},

    _refresh: function() {
        var _domains = JSON.parse(ExceptionsManager.uwa.permissions_get_all_domains().readString());

        if (_domains == ExceptionsManager.domains)
            return;

        ExceptionsManager.domains = _domains;

        var treeChildren = window.document.getElementById('treeChildren');
        while (treeChildren.hasChildNodes()) {
            treeChildren.removeChild(treeChildren.lastChild);
        }
        for (var i = 0; i < ExceptionsManager.domains['dontask'].length; i++) {
            var item = window.document.createElement("treeitem");
            var row = window.document.createElement("treerow");
            var cell = window.document.createElement("treecell");

            cell.setAttribute("label", ExceptionsManager.domains['dontask'][i]);

            item.appendChild(row);
            row.appendChild(cell);
            treeChildren.appendChild(item);
        }
    },

    onLoad: function() {
        window.document.getElementById('descrLabel').value = l10n.formatMessage('exceptionDialog.descrLabel');
        window.document.getElementById('closeButton').label = l10n.formatMessage('exceptionDialog.closeButton');
        window.document.getElementById('siteColumn').setAttribute('label', l10n.formatMessage('exceptionDialog.siteColumn'));
        ExceptionsManager._refresh();
        document.title = l10n.formatMessage('exceptionDialog.title');
    },

    onUnload: function() {
    },

    onAdd: function() {
        var site = window.document.getElementById('siteText');
        var value = site.value;

        if (!value)
            return;

        ExceptionsManager.uwa.permissions_dontask_domain(value);
        site.value = '';
        ExceptionsManager._refresh();
    },

    onSelect: function() {
        var button = window.document.getElementById('removeButton');
        button.setAttribute('disabled', 'false');
    },

    onRemove: function() {
        var button = window.document.getElementById('removeButton');
        var tree = window.document.getElementById('tree');
        button.setAttribute('disabled', 'true');

        if (tree.currentIndex == -1)
            return;

        ExceptionsManager.uwa.permissions_remove_domain_from_permissions(ExceptionsManager.domains['dontask'][tree.currentIndex]);
        ExceptionsManager._refresh();
    }
};
