/**
 * Permissions
 *
 * for PermissionsController (acl plugin)
 */

var AclPermissions = {
    baseUrl: window.location.protocol + '//' + window.location.hostname,
    spinner: "fa-spinner",
    checkMark: "fa-check",
    xMark: "fa-times"
};

AclPermissions._firstLoad = true;

// row/cell templates
AclPermissions.templates = {

    permissionRow: _.template('<tr data-parent_id="<%= id %>" class="<%= classes %>"> <%= text %> </tr>'),


    controllerCell: _.template('\
<td> \
	<div class="<%= classes %>" data-alias="<%= alias %>" \
		data-level="<%= level %>" data-id="<%= id %>" > \
	<%= alias %><i class="fa pull-right"></i> \
	</div> \
</td>'),

    toggleButton: _.template('\
<td><i class="<%= classes.trim() %>" \
		data-aro_id="<%= aroId %>" data-aco_id="<%= acoId %>"></i> \
</td>')

};

/**
 * functions to execute when document is ready
 *
 * @return void
 */
AclPermissions.documentReady = function () {
    AclPermissions.permissionToggle();
    AclPermissions.tableToggle();
    $('tr:has(div.controller)').addClass('controller-row');
};

/**
 * Toggle permissions (enable/disable)
 *
 * @return void
 */
AclPermissions.permissionToggle = function () {
    $('.permission-table').one('click', '.permission-toggle:not(.permission-disabled)', function () {
        var $this = $(this);
        var acoId = $this.data('aco_id');
        var aroId = $this.data('aro_id');

        // show loader
        $this
            .removeClass(AclPermissions.checkMark + ' ' + AclPermissions.xMark)
            .addClass(AclPermissions.spinner);

        // prepare loadUrl
        var loadUrl = AclPermissions.baseUrl + '/admin/permissions/toggle/';
        loadUrl += acoId + '/' + aroId + '/';

        // now load it
        var target = $this.parent();
        $.post(loadUrl, null, function (data, textStatus, jqXHR) {
            target.html(data);
            AclPermissions.permissionToggle();
        });

        return false;
    });
};

/**
 * Toggle table rows (collapsible)
 *
 * @return void
 */
AclPermissions.tableToggle = function() {

    // create table rows from json
    var renderPermissions = function(data, textStatus) {
        var $el = $(this);
        var rows = '';
        var id = $el.data('id');
        var spinnerClass = AclPermissions.spinner;
        for (var acoId in data.permissions) {
            text = '<td>' + acoId + '</td>';
            var aliases = data.permissions[acoId];
            for (var alias in aliases) {
                var aco = aliases[alias];
                var children = aco['children'];
                var classes = children > 0 ? 'controller perm-expand' : '';
                classes += " level-" + data.level;
                text += AclPermissions.templates.controllerCell({
                    id: acoId,
                    alias: alias,
                    level: data.level,
                    classes: classes.trim()
                });
                text += renderGroups(data.aros, acoId, aco);
            }
            var rowClass = '';
            if (children > 0 && data.level > 0) {
                rowClass = "controller-row level-" + data.level;
            }
            rows += AclPermissions.templates.permissionRow({
                id: id,
                classes: rowClass,
                text: text
            });
        }
        var $row = $el.parents('tr');
        $(rows).insertAfter($row);
        $el.find('i').removeClass(spinnerClass);
    };

    // create table cells for role permissions
    var renderGroups = function(aros, acoId, groups) {
        var text = '';
        for (var aroIndex in groups['groups']) {
            var cell = {
                aroId: aros[aroIndex],
                acoId: acoId,
                classes: "permission-toggle fa "
            };
            if (groups['children'] > 0) {
                text += '<td>&nbsp;</td>';
                continue;
            }

            var allowed = groups['groups'][aroIndex];
            if (aroIndex == 1) {
                cell.classes += "lightgray permission-disabled " + AclPermissions.checkMark;
            } else {
                if (allowed) {
                    cell.classes += "green " + AclPermissions.checkMark;
                } else {
                    cell.classes += "red " + AclPermissions.xMark;
                }
            }
            text += AclPermissions.templates.toggleButton(cell);
        }
        return text;
    };

    $('.permission-table').on('click', '.controller', function() {
        var $el = $(this);
        var id = $el.data('id');
        var level = $el.data('level');
        var spinnerClass = AclPermissions.spinner;

        $el.find('i').addClass(spinnerClass);
        if ($el.hasClass('perm-expand')) {
            $el.removeClass('perm-expand').addClass('perm-collapse');
        } else {
            var children = $('tr[data-parent_id=' + id + ']');
            children.each(function() {
                var childId = $('.controller', this).data('id')
                var grandchildren = $('tr[data-parent_id=' + childId + ']');
                grandchildren.each(function() {
                    var grandchildId = $('.controller', this).data('id');
                    $('tr[data-parent_id=' + grandchildId + ']').remove();
                })
                $('tr[data-parent_id=' + childId + ']').remove();
            }).remove();
            $el.removeClass('perm-collapse').addClass('perm-expand')
                .find('i').removeClass(spinnerClass);
            return;
        }

        var params = {
            perms: true
        };

        var url = AclPermissions.baseUrl + '/admin/permissions/index/';
        $.getJSON(url + id + '/' + level, params, function(data, textStatus) {
            renderPermissions.call($el[0], data, textStatus);
        });
    });
};

/**
 * document ready
 *
 * @return void
 */
$(document).ready(function () {
    AclPermissions.documentReady();
});
