/// class ProspectDirector.Web.UI.Canvas.Charts.ChartAnchorsFeature
/// using ProspectDirector.Web.UI.FeatureSets.MacroEditorBase

/**
@class ChartAnchorsFeature
@constructor
@namespace Web.UI.Canvas.Charts
@extends Web.UI.FeatureSets.MacroEditorBase
**/
ProspectDirector.Web.UI.Canvas.Charts.ChartAnchorsFeature = ProspectDirector.Web.UI.FeatureSets.MacroEditorBase.extend({

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

    _gridDomNode: null,
    _gridWrapperDomNode: null,
    _addButton: null,
    _clearButton: null,

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

    get_grid: function () {
        return this.get_gridDomNode().data("kendoGrid");
    },

    get_gridDomNode: function () {
        return this._gridDomNode;
    },

    get_gridWrapperDomNode: function () {
        return this._gridWrapperDomNode;
    },

    get_addButton: function () {
        return this._addButton;
    },

    get_clearButton: function () {
        return this._clearButton;
    },

    //==============================
    // INITIALIZERS
    //==============================

    _init_controls: function () {

        this._gridDomNode = this.get_element().find("[data-id=grid]");
        this._gridWrapperDomNode = this.get_element().find("[data-id=grid-wrapper]");
        this._addButton = this.get_element().find("[data-id=add]");
        this._clearButton = this.get_element().find("[data-id=clear]");

        this._init_grid();

        this.get_addButton().on("click", $.proxy(this._addButton_onClick, this));
        this.get_clearButton().on("click", $.proxy(this._clearButton_onClick, this));

    },

    _init_grid: function () {

        var that = this,
            entityTypes = this.getValue("entityTypes");

        if (!entityTypes) {
            entityTypes = { groups: [] };
        }

        this.get_gridDomNode().kendoGrid({
            dataSource: {
                data: entityTypes.groups,
                schema: {
                    model: {
                        id: "depth"
                    }
                }
            },
            height: "100%",
            columns: [
                {
                    title: "&nbsp;",
                    field: "icon",
                    width: 25,
                    attributes: {
                        style: "vertical-align:top;"
                    },
                    template: function (e) {

                        var index = that.get_grid().dataSource.indexOf(e);

                        if (index === 0) {
                            return "<img src=\"" + ProspectDirector.RUNTIME.resolveUrl("~/application/icons/16x16/target.png") + "\"/>";
                        }
                        else {
                            return "<img src=\"" + ProspectDirector.RUNTIME.resolveUrl("~/application/icons/16x16/arrow_up_blue.png") + "\"/>";
                        }

                    }
                },
                {
                    title: "Target",
                    field: "target",
                    width: 100,
                    attributes: {
                        style: "vertical-align:top;font-weight:bold;"
                    },
                    template: function (e) {

                        var index = that.get_grid().dataSource.indexOf(e);

                        if (index === 0) {
                            return "Target";
                        }
                        else {
                            return "Ancestor " + index;
                        }

                    }
                },
                {
                    title: "Group",
                    field: "parts",
                    template: function (e) {

                        var index = 0,
                            result = [];

                        for (index; index < e.types.length; index++) {
                            result[result.length] = e.types[index].name;
                        }

                        return result.join("<br/>");

                    }
                }
            ],
            dataBound: function () {

                if (that.get_grid().dataSource.data().length > 0) {
                    ProspectDirector.Web.UI.Utilities.Kendo.Grid.removeMessage(that.get_gridDomNode());
                }
                else {
                    ProspectDirector.Web.UI.Utilities.Kendo.Grid.addMessage(that.get_gridDomNode(), "No anchors have been selected.");
                }

            }
        });

    },

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

    _addButton_onClick: function (e) {
        ProspectDirector.Web.UI.Queries.SelectAnchorDialog.open({
            callbacks: {
                ok: $.proxy(this._anchors_onAdd, this)
            }
        });
    },

    _clearButton_onClick: function (e) {

        var that = this;

        ProspectDirector.Web.UI.MessageDialog.confirm({
            message: "Clear all the anchors for this chart?<br/><br/>This will remove all Fields, Value Fields, Legend Fields and Category Fields from your chart.",
            buttons: {
                proceed: {
                    label: "Continue",
                    callback: function (e) {
                        that.setValue("entityTypes", { groups: [] });
                        that.get_eventBus().publish("reload-target", true);
                    }
                },
                cancel: "Cancel"
            }
        });

    },

    _anchors_onAdd: function (sender, e) {
        this._update(e.selections);
        this.get_eventBus().publish("reload-target", true);
    },

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

    activate: function () {
        this._init_controls();
    },

    render: function () {

        var result = "" +

        "<div id=\"" + this.getId() + "\" style=\"padding:10px;\">" +
            "<div class=\"-pd-macro-editor-description\">" +
            "Add anchors to restrict the results of your query to specific entity types and gain access to data specific to those entity types." +
            "</div>" +
            "<div data-id=\"grid-wrapper\" style=\"border:1px solid #AAAAAA;margin-right:20px;\">" +
                "<div data-id=\"grid\" style=\"border:0px;\"></div>" +
            "</div>" +
            "<div style=\"margin-top:10px;height:25px;overflow:hidden;white-space:nowrap;\">" +
            "<button data-id=\"add\" class=\"pd-button\">Add</button>&nbsp;" +
            "<button data-id=\"clear\" class=\"pd-button\">Clear</button>" +
            "</div>" +
        "<div>";

        return result;

    },

    size: function (e) {

        var wrapper = this.get_element().find("DIV[data-id=grid-wrapper]"),
            grid = this.get_element().find("DIV[data-id=grid]");

        this.get_element().height(e.height);
        this.get_element().width(e.width);
        wrapper.width(e.width - 2);
        wrapper.height(e.height - 72);

        var filler = new ProspectDirector.Web.UI.Utilities.Kendo.Grid.Fill({
            selector: this.get_element().find("DIV[data-role=grid]").selector,
            useAvailableSpace: false
        });

        filler.size();

    },

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

    _update: function (groups) {

        var that = this,
            data = this.getValue("entityTypes"),
            copy = $.extend(true, {}, data);

        groups.each(function (index, group) {
            that._iterateTypes(group.types, copy);
        });

        this.setValue("entityTypes", copy);

        this.get_grid().dataSource.data(copy.groups);
        this.get_grid().refresh();

    },

    _iterateTypes: function (types, copy) {

        var that = this;

        types = new ProspectDirector.Web.List(types);

        types.each($.proxy(function (index, type) {
            that._setGroup(index, type, copy);
        }, this));

    },

    _setGroup: function (index, type, copy) {

        var data = new ProspectDirector.Web.List(copy.groups),
            group = data.getAtIndex(index),
            exists = !!group;

        if (!exists) {

            group = {
                depth: index,
                target: index === 0 ? "Target" : "Ancestor " + index,
                types: []
            };

            data.add(group);

        }

        this._setType(group, type);

    },

    _setType: function (group, type) {

        if (!this._hasType(type.id, group.types)) {
            group.types.push(type);
        }

    },

    _hasType: function (typeId, types) {

        var index = 0,
            result = false;

        for (index; index < types.length; index++) {
            if (types[index].id === typeId) {
                result = true;
                index = types.length;
            }
        }

        return result;

    }

});