/// class ProspectDirector.Web.UI.Queries.SelectColumnsDialogDOM
/// using ProspectDirector.Web.UI.SelectionDialogBaseDOM

/**
@class SelectColumnsDialogDOM
@namespace Web.UI.Queries
@constructor
**/
ProspectDirector.Web.UI.Queries.SelectColumnsDialogDOM = ProspectDirector.Web.UI.SelectionDialogBaseDOM.extend({

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

    get_searchDepth: function () {
        return this.get_container().find("[data-id=search-depth-input]");
    },

    get_searchCategories: function () {
        return this.get_container().find("[data-id=search-category-input]");
    },

    get_gridLabel: function () {
        return this.get_container().find("[data-id=grid-label]");
    },

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

    _init_searchCategories: function () {

        var items = new ProspectDirector.Web.List(),
            $target = $("<optgroup data-group=\"target\" label=\"Anchor Group\"></optgroup>"),
            $referenced = $("<optgroup  data-group=\"reference\" label=\"Anchor Group References\"></optgroup>");

        items.add({ name: "All", value: 0 });
        items.add({ name: "Common", value: 1 });
        items.add({ name: "Single Select Lists", value: 2 });
        items.add({ name: "Multi-Select Lists", value: 3 });

        items.each(function (index, item) {
            $target.append("<option value=\"" + item.value + "\" data-name=\"" + item.name + "\">" + item.name + "</option>");
            $referenced.append("<option value=\"" + item.value + "\" data-name=\"" + item.name + "\">" + item.name + "</option>");
        });

        $target.find(":eq(1)").attr("selected", "selected");

        this.get_searchCategories().append($target);
        this.get_searchCategories().append($referenced);

        this.get_searchCategories().on("change", $.proxy(this._searchCategories_onChange, this));

        this._updateGridLabel();

    },

    _init_searchDepth: function () {

        var that = this,
            items = "",
            depths = this.options.depths;

        depths.each(function (index, item) {
            items += "<option value=\"" + item.value + "\">" + item.name + "</option>";
        });

        this.get_searchDepth().append(items);

        this.get_searchDepth().on("change", function (e) {
            that.refreshGrid();
        });

    },

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

    _searchCategories_onChange: function (e) {

        this._updateGridLabel();

        this.refreshGrid();

    },

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

    activate: function () {
        this._init_searchDepth();
        this._init_searchCategories();
        this._super();
    },

    render: function () {

        var content = "" +
        "<div class=\"-pd-dlg-select-query-columns\">" +
        "<label data-id=\"search-category-label\">Show fields from:</label>" +
        "<div data-id=\"search-category\">" +
        "<select data-id=\"search-category-input\"></select>" +
        "</div>" +
        "<label data-id=\"search-depth-label\">Anchor group:</label>" +
        "<div data-id=\"search-depth\">" +
        "<select data-id=\"search-depth-input\"></select>" +
        "</div>" +
        "<label data-id=\"grid-label\">Fields</label>" +
        "<div data-id=\"search-box\"></div>" +
        "<div data-id=\"grid-wrapper\">" +
        "<div data-id=\"grid\"></div>" +
        "</div>" +
        "<div data-id=\"dialog-button-deck\">" +
        "<button data-id=\"ok\" class=\"-pd-button\">OK</button>" +
        "&nbsp;" +
        "<button data-id=\"cancel\" class=\"-pd-button\">Cancel</button>" +
        "</div>" +
        "</div>";

        this.get_container().empty();

        this.get_container().append(content);

    },

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

    setGridOptions: function (options) {

        var url = "~/query/" + (this.options.filterable ? "findfilterablecolumn" : "findcolumn");

        return this._super({
            dataSource: {
                schema: {
                    data: "columns",
                    total: "totalCount",
                    model: {
                        id: "id"
                    }
                },
                transport: {
                    read: {
                        url: ProspectDirector.RUNTIME.resolveUrl(url)
                    }
                },
                sort: {
                    field: "name",
                    dir: "asc"
                }
            },
            columns: [
                { title: "Name", field: "name", width: 150 },
                { title: "Used By", field: "usedBy", width: 150 },
                { title: "Found In", field: "foundIn", width: 400 },
                { width: 1000 }
            ]
        });

    },

    setGridSelectionOptions: function (options) {
        return this._super({
            primaryKey: "id"
        });
    },

    getGridRequestParameters: function (data, type) {

        var isReferenceGroup = this._isCategoryGroup("reference");

        return {
            request: JSON.stringify({
                anchor: this.options.anchor,
                category: this.get_searchCategories().val() * 1,
                references: isReferenceGroup,
                condense: true,
                depth: this.get_searchDepth().val() * 1,
                exclude: [],        //TODO: set this value using params passed to the dialog.
                include: [],        //TODO: set this value using params passed to the dialog.
                names: {},          //TODO: set this value using params passed to the dialog.
                keywords: this.get_searchBox().getValue(),
                orders: this.getGridSortOrder(data.sort),
                pageIndex: data.page - 1,
                pageSize: data.pageSize,
                templateId: this.options.templateId
            })
        };

    },

    getGridSortOrder: function (arr) {

        var result = new ProspectDirector.Web.List(),
            sorts = new ProspectDirector.Web.List(arr),
            sortColumnId = {
                name: 0,
                usedBy: 1,
                foundIn: 2
            };

        sorts.each(function (index, sort) {

            result.add({
                ascending: sort.dir === "asc",
                column: sortColumnId[sort.field]
            });

        });

        return result.toArray();

    },

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

    _updateGridLabel: function () {

        var isReferenceGroup = this._isCategoryGroup("reference"),
            value = this.get_searchCategories().val(),
            $selection = this.get_searchCategories().find(":selected");

        if (isReferenceGroup) {
            label = "Anchor Group Reference";
        }
        else {
            label = "Anchor Group";
        }

        this.get_gridLabel().html("Displaying " + label.toLowerCase() + " fields");

    },

    _isCategoryGroup: function (category) {

        var option = this.get_searchCategories().find(":selected"),
            parent = option.parent();

        return parent.data("group") === category;

    }

});