/// class PD.Web.UI.Controls.Security.AclEditor
/// using PD.Web.UI.Controls.Control

PD.Web.UI.Controls.Security.AclEditor =
PD.Web.UI.Controls.Control.extend({

    //===================================
    // FIELDS
    //===================================

    _grid: null,

    //===================================
    // CONSTRUCTOR
    //===================================

    init: function (options) {
        this._super($.extend({
            aces: []
        }, options));
    },

    //===================================
    // PROPERTIES
    //===================================

    get_grid: function () {
        return this._grid;
    },

    //===================================
    // EVENT HANDLERS
    //===================================

    grid_onChange: function (sender, e) {

        var callbackFn = this.get_options()["change"];
        var selections = this.get_grid().getSelections().toArray();;
        var selection = _.first(selections);

        if (_.isFunction(callbackFn)) {
            callbackFn(selection != null ? selection.toJSON() : null);
        }

    },

    onInit: function () {
        this.grid_init();
    },

    //===================================
    // PUBLIC METHODS
    //===================================

    addAce: function (aces, clear) {

        if (aces == undefined) {
            this.showIdentityFinderDialog();
            return;
        }

        if (_.isArray(aces)) {
            this.addAces(aces, {clear: clear, select: true});
        }

    },
    
    removeAce: function () {

        var record = _.first(this.get_grid().getSelections().toArray());
        var grid = this.get_grid();
        var ds = grid.get_dataSource().get_instance();

        if (record != null) {

            if (record.inherited !== undefined && record.inherited !== null) {
                this.showAceRemovalDeniedDialog(record);
            }
            else {
                ds.remove(record);
                grid.refresh({
                    clear: true
                });
            }

        }

    },

    redraw: function() {
        this._grid.redraw();
    },

    clear: function () {

        var ds = this._grid.get_dataSource();
        var remove = ds.get_instance().data().slice(0);

        _.each(remove, function (item) {
            ds.get_instance().remove(item);
        });

    },

    updateAce: function (ace) {

        var record = this.get_grid().get_dataSource().get_instance().get(ace.id);

        if (record != null) {
            record.allow = ace.allow;
            record.deny = ace.deny;
            this.get_grid().refresh();
        }

    },

    getAcl: function () {
        return this.get_grid().get_dataSource().data().toJSON();
    },

    //===================================
    // PROTECTED METHODS
    //===================================

    template: function (options) {
        return [
            "<div class='-pd-acl-editor'>",
                "<div class='-pd-acl-editor-header'>",
                    "<label>",
                        "Users and Groups",
                    "</label>",
                "</div>",
                "<div data-id='grid' class='-pd-acl-editor-grid' style='border:1px solid #CCCCCC;'></div>",
            "</div>"
        ];
    },

    //===================================
    // PRIVATE METHODS
    //===================================

    grid_init: function () {

        this._grid = new PD.Web.UI.Controls.Grid({
            insertAt: "div[data-id=grid]",
            pk: "id",
            selectionMode: "single",
            messaging: {
                noRecordsMessage: "No access entries exist."
            },
            dataSource: {
                data: this.get_options().aces,
                sort: [
                    { field: "name", dir: "asc" }
                ],
                storeAsLocalVariable: true
            },
            schema: {
                model: {
                    id: "id"
                }
            },
            change: _.bind(this.grid_onChange, this),
            footer: {
                visible: false
            },
            columns: [
                new PD.Web.UI.Controls.GridIconColumn({
                    title: "",
                    width: 25,
                    attributes: {
                        style: "text-align:center;padding:0px;padding-top:3px;"
                    },
                    transform: function (e) {
                        return (e.type === 0 ? "USER.PNG" : "USERS.PNG");
                    }
                }),
                new PD.Web.UI.Controls.GridColumn({
                    title: "Name",
                    field: "name"
                }),
                new PD.Web.UI.Controls.GridColumn({
                    title: "Type",
                    field: "inherited",
                    width: 100,
                    template: function (e) {
                        var result = "";
                        var isInherited = e.inherited != null;
                        var isOverridden = null;
                        if (isInherited) {
                            isOverridden = (e.inherited.allow != e.allow || e.inherited.deny != e.deny);
                            result = isOverridden ? "<span style=\"text-decoration:line-through;\">Inherited</span>" : "Inherited";
                        }
                        return result;
                    }
                })
            ]
        });

        this.get_children().add(this._grid);

    },

    addAces: function (aces, options) {

        var ace = null;
        var grid = this._grid;
        var ds = grid.get_dataSource();
        var data = [];
        var selections = [];
        var isDuplicate = function (addition) {

            var result = false;

            _.each(ds.data(), function (item) {
                if (addition.id === item.id) {
                    result = true;
                    return false;
                }
            });

            return result;

        };

        options = _.extend({
            clear: false,
            select: true
        }, options);

        _.each(aces, function (item) {

            ace = _.extend({
                allow: 0,
                deny: 0,
                inherited: null
            }, item);

            if (!isDuplicate(item)) {
                data[data.length] = item;
                selections = [ace.id];
            }

        });

        if (options.clear === true) {
            this.clear();
        }

        ds.data().push.apply(ds.data(), data);

        if (options.select === true && selections.length > 0) {
            grid.refresh({
                selections: selections
            });
        }

    },

    showIdentityFinderDialog: function () {

        var that = this;
        
        PDJS.Shared.Security.IdentityBrowserDialog.open({
            title: "Add Users and Groups",
            filters: [
                PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
            ],
            callbacks: {
                ok: function (sender, e) {
                    that.addAces(e, {
                        clear: false,
                        select: true
                    });
                }
            }
        });
        
    },

    showAceRemovalDeniedDialog: function (record) {

        var grid = this.get_grid();

        Jade.UI.MessageDialog.open({
            dialogStyle: Jade.UI.MessageDialogStyle.Error,
            dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNo,
            title: "Cannot Remove ACE",
            message: `Inherited entries cannot be removed.<br/><br/>Do you want to set the entry to use its inherited permissions instead?`,
            select: (e) => {
                e.close();
                if (e.button === Jade.UI.MessageDialogButton.yes) {
                    record.allow = record.inherited.allow;
                    record.deny = record.inherited.deny;
                    grid.refresh();
                }
            }
        });

    }

});