// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @constructor
 * @type {DisplayListView}
 */
define(['hp/core/Notifications',
        'hp/core/Localizer',
        'hp/core/Router',
        'hp/view/DialogView',
        'text!hpPages/common/display-items-list.html',
        'jquery',
        'hp/lib/jquery.hpCollapsible',
        'lib/jquery.validate'],
function(notifications, Localizer, router, DialogView, displayItemListHtml) {"use strict";

    var DisplayListView = ( function() {

        var DISPLAY_SECTION ="#cic-displayitemlist-section",
            SUBHEADER = '#cic-displayitemlist-subheader',
            TITLE_BAR = '#cic-displayitemlist-title',
            TITLE_BAR_TEXT = TITLE_BAR + ' h1',
            LABEL = '#cic-displayitemlist-label',
            SPINNER = '#cic-displayitemlist-spinner',
            ITEMS_TABLE_ID = '#cic-displayitemlist-items-table',
            CLOSE = '#cic-displayitemlist-close-button',
            NOTIFY_BOX = '#cic-displayitemlist-details-notify',
            NOTIFY_MSG = "#cic-displayitemlist-notify-message-id",
            NOTIFICATION_CLASS = "hp-details-notify ",
            NOTIFICATION_COLOR_PREFIX = "hp-details-notify-",
            DISMISS = "#cic-displayitemlist-notify-dismiss_link",
            HELP_LINK ="#cic-displayitemlistnotify-help_link",
            LOCATION_CHANGE = 'locationChange';

        /**
         * Constructor
         */
        function DisplayListView() {
            var itemType = '',
                dialog = null,
                helpLink = '#',
                dataLoaded = false,
                tableInitialized = false,
                itemsTable = null,
                getItemsFunction = null,
                objectItemList = null,
                container = null;

            /**
             * @private
             */
            function notification(message,messageType) {
                $(NOTIFY_MSG, container).html(message);
                $(NOTIFY_BOX, container).attr('class', NOTIFICATION_CLASS + NOTIFICATION_COLOR_PREFIX+ messageType);
                $(NOTIFY_BOX, container).fadeIn();
                $(HELP_LINK, container).attr('href',helpLink);
            }

            /**
             * Called after a successful get items operation
             */
            function onGetItemsSuccess(items) {
                $(DISPLAY_SECTION, container).show();
                if(objectItemList !== null) {
                    itemsTable.fnAddData(items[objectItemList]);
                } else {
                    itemsTable.fnAddData(items);
                }

                $(SPINNER, container).hide();
                dataLoaded = true;
            }

            /**
             * Called after an unsuccessful get items operation
             */
            function onGetItemsError(errorMessage) {
                $(SPINNER, container).hide();
                var updateMsg = Localizer.getString('fs.displayItemList.get_failed', [itemType]);
                notifications.show(updateMsg);

                var alertMsg = Localizer.formatRestError(updateMsg,errorMessage);
                notification(alertMsg,"error");
                dataLoaded = true;
                $(DISPLAY_SECTION, container).show();
            }

            /**
             * Populate the data table of items
             */
            function populateItems(args) {
                getItemsFunction({
                    success : function(items) {
                        onGetItemsSuccess(items);

                        if ($(SUBHEADER, container).parent(LABEL).length) {
                            $(SUBHEADER, container).unwrap();
                            $(DISPLAY_SECTION, container).removeClass();
                        }
                        if (args.collapsible) {
                            var labelWrapper = document.createElement('label');
                            labelWrapper.id = "cic-displayitemlist-label";
                            $(SUBHEADER, container).wrap(labelWrapper);
                            $(LABEL, container).unbind();
                            $(DISPLAY_SECTION, container).hpCollapsible();
                            $(LABEL, container).click(function(){$(SPINNER).hide();});
                        }

                        if (args.displayFunction) {
                            args.displayFunction();
                        }
                    },
                    error : onGetItemsError
                });
            }

            /**
             * The page hash has changed, close the dialog
             */
            function onLocationChange() {
                if (dialog) {
                    dialog.cancel();
                }
            }
            
            function setDialog(args) {
                dialog = new DialogView({contents: $(container)});

                if(args.hideTitleBar){
                    $(TITLE_BAR, container).hide();
                } else  {
                    $(TITLE_BAR, container).show();
                }

                if(args.preDisplayFunction) {
                    args.preDisplayFunction();
                }

                if (args.currentItemName) {
                    $(TITLE_BAR_TEXT, container).html(args.currentItemName);
                }
            }

            /**
             * @public
             * function to make the dialog visible
             * and load items into the list
             */
            this.showDialog = function(args) {
                $(DISPLAY_SECTION, container).hide();
                $(NOTIFY_BOX, container).hide();
                $(SPINNER, container).show();

                getItemsFunction = args.getItemsFunction;
                objectItemList = args.objectList;
                itemType = args.itemType;

                if(args.cleanupFunction) {
                    var keyDownFunc;

                    var cleanup = function(ev) {
                        args.cleanupFunction();
                        $(CLOSE, container).unbind('click', cleanup);
                        router.off(LOCATION_CHANGE, cleanup);
                        $(document).unbind('keydown', keyDownFunc);
                    };

                    keyDownFunc = function(ev) {
                        if(ev.keyCode === 27) {
                            cleanup(ev);
                        }
                    };

                    $(document).keydown(keyDownFunc);

                    $(CLOSE, container).click(cleanup);

                    router.on(LOCATION_CHANGE, cleanup);
                }

                helpLink = "#";
                if(args.helpLink) {
                    helpLink = args.helpLink;
                }

                if(args.warningMsg) {
                    notification(args.warningMsg,"warning");
                    $(HELP_LINK, container).hide();
                    $(DISMISS, container).hide();
                }

                $(SUBHEADER, container).hide();
                if(args.message) {
                    $(SUBHEADER, container).html(args.message);
                    $(SUBHEADER, container).show();
                }

                /**
                 * Setup the table
                 */
                var columns = args.columns;
                var options = {
                        "sScrollY" : "250px",
                        "sScrollX" : "260px",
                        "sScrollXInner" : "100%",
                        "bDestroy" : true,
                        "bPaginate" : false,
                        "bFilter" : false,
                        "bInfo" : false,
                        "bAutoWidth": false,
                        "aaData" : [],
                        "aoColumns" : columns
                };
                
                if(args.sScrollY) {
                    options.sScrollY = args.sScrollY;
                }

                if(args.sScrollX) {
                    options.sScrollX = args.sScrollX;
                }

                if(args.aaSorting) {
                    options.aaSorting = args.aaSorting;
                }

                if(itemsTable && itemsTable.length > 0){//fix problem with columns being messed up on re-creation of table
                    itemsTable.fnDestroy();
                    $("thead", $(ITEMS_TABLE_ID, container)).remove();
                }
                itemsTable = $(ITEMS_TABLE_ID, container).dataTable(options);

                /**
                 * add row selection capabilities
                 */
                if(!tableInitialized) {
                    tableInitialized = true;
                }

                dataLoaded = false;

                setDialog(args);
                populateItems(args);
            };

            this.getDataTable = function() {
                return itemsTable;
            };

            this.init = function() {
                if (container === null) {
                    container = $(displayItemListHtml);
                    Localizer.localizeDom(container);
                    // hide it until showDialog is called.
                    $(DISPLAY_SECTION, container).hide();
    
                    //if the location changed, close the dialog
                    router.on(LOCATION_CHANGE, onLocationChange);

                    // close the notifications
                    $(DISMISS, container).click(function (evt) {
                        evt.preventDefault();
                        $(NOTIFY_BOX, container).slideUp();
                    });
                }
            };
        }

        return new DisplayListView();
    }());
    return DisplayListView;
});
