/// class ProspectDirector.Modules.Views.ViewSearchConfiguration
/// using ProspectDirector.Types.Core.Dialog
/// using ProspectDirector.Types.Core.ContextMenu

ProspectDirector.Modules.Views.ViewSearchConfiguration = (function (options) {

    var 

    PRIVATE = {

        //---------------------------
        //--- CONSTRUCTOR
        //---------------------------

        init: function () {

            options = $.extend({
                selector: null,
                viewStateId: null,
                data: null,
                type: null
            }, options);

            PRIVATE.init_container();
            PRIVATE.init_menu();
            PRIVATE.init_tree();

        },

        //---------------------------
        //--- PROPERTIES
        //---------------------------

        get_container: function () {
            return $(options.selector);
        },

        get_menu: function () {
            return PRIVATE.get_container().find("[data-role=menu]");
        },

        get_tree: function () {
            return PRIVATE.get_container().find("[data-role=treeview]");
        },

        //---------------------------
        //--- INITIALIZERS
        //---------------------------

        init_container: function () {

            PRIVATE.get_container().data("contextMenu", new ProspectDirector.Modules.Views.ViewSearchConfiguration.ContextMenu({
                parent: PRIVATE
            }));

        },

        init_menu: function () {

            PRIVATE.get_menu().kendoMenu({
                select: $.proxy(PRIVATE.menu_onSelect, PRIVATE)
            });

        },

        init_tree: function () {

            var info = null;

            PRIVATE.get_tree().kendoTreeView({
                dataBound: $.proxy(PRIVATE.tree_onDataBound, PRIVATE)
            });

            PRIVATE.get_tree().parent().css({
                border: "1px solid #AAAAAA",
                paddingTop: "5px",
                paddingLeft: "0px",
                height: "300px",
                overflow: "auto",
                fontSize: "12px",
                fontFamily: "Arial",
                backgroundColor: "#FFFFFF"
            });

            if (options.data.length === 0) {
                PRIVATE.addNoColumnsMessage();
            }
            else {
                PRIVATE.populate(options.data);
            }

        },

        //---------------------------
        //--- EVENT HANDLERS
        //---------------------------

        menu_onSelect: function (e) {

            var command = $(e.item).data("command"),
                tree = PRIVATE.get_tree().data("kendoTreeView");

            switch (command) {
                case "add":
                    PRIVATE.showFinderDialog();
                    break;
                case "remove":
                    PRIVATE.remove(tree.select());
                    break;
                case "clear":
                    PRIVATE.get_tree().children("LI").each(function (index, element) {
                        PRIVATE.remove($(element));
                    });
                    break;
            }

        },

        tree_onDataBound: function (e) {

            var tree = PRIVATE.get_tree().data("kendoTreeView"),
                data = null,
                index = 0;

            if (e.node === undefined || e.node.length === 0) {
                data = e.sender.dataSource._data;
            }
            else {
                data = tree.dataItem(e.node).children._data;
            }

            if (data !== undefined) {

                for (index = 0; index < data.length; index++) {
                    PRIVATE.nodeTemplate(data[index]);
                }

            }

        },

        finderDialog_onOk: function (e, sibling) {

            var tree = PRIVATE.get_tree().data("kendoTreeView"),
                index = 0;

            PRIVATE.removeMessageNodes();

            for (index = 0; index < e.length; index++) {
                if (!PRIVATE.columnExists(e[index].id)) {
                    PRIVATE.addColumn(e[index], sibling);
                }
            };

        },

        //---------------------------
        //--- METHODS
        //---------------------------

        addNoColumnsMessage: function () {

            PRIVATE.get_tree().data("kendoTreeView").append({
                text: "No columns have been added, the defaults will be used."
            });

        },

        removeMessageNodes: function () {
            PRIVATE.get_tree().data("kendoTreeView").remove(PRIVATE.get_tree().find("li[data-message=true]"));
        },

        nodeTemplate: function (data) {

            var $span = $("<span></span>"),
                $node = PRIVATE.get_tree().data("kendoTreeView").findByUid(data.uid),
                $inner = $node.find(".k-in").first(),
                info = data.info;

            if (info !== undefined) {

                if (info.ref !== undefined) {
                    $node.attr("data-ref", info.ref);
                }

                $node.attr("data-role", "column");

                $span.html(info.name ? info.name : info.sysname);


            }
            else {

                $node.attr("data-message", "true");
                $inner.css({
                    backgroundColor: "#FFFFFF",
                    borderColor: "#FFFFFF"
                });
                $span.css({
                    color: "#AAAAAA",
                    fontStyle: "italic"
                });
                $span.html(data.text);

            }

            $inner.empty();
            $inner.html($span[0].outerHTML);

        },

        addColumn: function (data, sibling) {

            var guid = ProspectDirector.RUNTIME.guid(),
                node = null,
                info = null,
                tree = PRIVATE.get_tree().data("kendoTreeView");

            info = {
                info: {
                    ref: guid,
                    role: "column",
                    id: data.id,
                    name: data.name,
                    sysname: data.sysname,
                    width: null
                }
            }

            if (sibling === undefined || sibling === null) {
                node = tree.append(info)
            }
            else {
                node = tree.insertAfter(info, sibling);
            }

            return node;

        },

        populate: function (data) {

            var index = 0;

            for (index = 0; index < data.length; index++) {
                PRIVATE.addColumn(data[index]);
            }

        },

        getData: function () {

            var nodes = PRIVATE.get_tree().find("LI[data-role=column]"),
                tree = PRIVATE.get_tree().data("kendoTreeView"),
                result = [];

            nodes.each(function (idx, element) {
                result[result.length] = tree.dataItem(element).info;
            });

            return result;

        },

        remove: function (node) {

            var next = null,
                tree = PRIVATE.get_tree().data("kendoTreeView");

            if (node.length === 0) {
                return;
            };

            next = node.prev();

            if (next.length === 0) {
                next = node.next();
            };

            if (next.length === 0) {
                next = node.parent().closest("li.k-item");
            };

            tree.remove(node);
            tree.select(next);

            if (PRIVATE.get_tree().find("li.k-item").length === 0) {
                PRIVATE.addNoColumnsMessage();
            }

        },

        showFinderDialog: function (parentNode) {

            var dialog = ProspectDirector.Modules.Views.ViewSearchConfiguration.BoundsColumnFinder;

            dialog.show({
                params: {
                    viewStateId: options.viewStateId,
                    textOnly: true
                },
                callbacks: {
                    ok: $.proxy(function (sender, e) {
                        PRIVATE.finderDialog_onOk(e, parentNode);
                    }, PRIVATE)
                }
            });

        },

        columnExists: function (id) {

            var tree = PRIVATE.get_tree().data("kendoTreeView"),
                data = tree.dataSource._data,
                index = 0;

            for (index = 0; index < data.length; index++) {
                if (data[index].info.id === id) {
                    return true;
                }
            }

            return false;

        }

    },

    PUBLIC = {
        getData: PRIVATE.getData
    };

    PRIVATE.init();

    return PUBLIC;

});

//---------------------------
//--- STATIC METHODS
//---------------------------

ProspectDirector.Modules.Views.ViewSearchConfiguration.BoundsColumnFinder = 
new (ProspectDirector.Types.Core.Dialog.extend({
    
    init: function () {
        this._super("FindColumnInBounds",
                "Find Column",
                ProspectDirector.RUNTIME.resolveUrl("~/viewcolumn/findinbounds"));
    }

}));

//---------------------------
//--- INNER CLASSES
//---------------------------

ProspectDirector.Modules.Views.ViewSearchConfiguration.ContextMenu = ProspectDirector.Types.Core.ContextMenu.extend({

    //---------------------------
    //--- CONSTRUCTOR
    //---------------------------

    init: function (options) {
        this._super(options);
    },

    //---------------------------
    //--- PROPERTIES
    //---------------------------

    get_parent: function () {
        return this.options.parent;
    },

    get_contextMenuSelector: function () {
        return this.get_parent().get_tree().selector + " .k-item[data-uid][data-role]";
    },

    //---------------------------
    //--- PROTECTED METHODS
    //---------------------------

    _executeCommand: function (command, e) {

        switch (command) {
            case "add":
                this.get_parent().showFinderDialog(e.$trigger);
                break;
            case "remove":
                this.get_parent().remove(e.$trigger);
                break;
        }

    },

    _configureContextMenu: function (sender, e) {

        var info = this.get_parent().get_tree().data("kendoTreeView").dataItem(sender).info,
            items = e.config.items;

        items.add = {
            name: "Add Column..."
        };

        items.sep1 = "sep1";

        items.remove = {
            name: "Remove"
        };

    }

});
