// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hpsum/presenter/enclosure/EnclosurePresenter',
    'hp/core/Router',
    'hp/view/FormStateView',
    'hp/core/HelpMenu',
    'hp/core/localizer',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpToggle'],
function(presenter, router, FormStateView, helpMenu, localizer) { "use strict";

    var EnclosureAddView = (function() {
      
        var ADD = '#tour-enclosure-add',
            ADD_AGAIN = '#tour-enclosure-add-again',
            CANCEL = '#tour-enclosure-add-cancel',
            RESET = "#tour-enclosure-reset",
            PANEL_SELECTOR = '#tour-enclosure-add-panel-selector',
            FIRST_ANCHOR = PANEL_SELECTOR + ' a[href]:first',
            PANELS = '#tour-enclosure-add-panels',
            TITLE = '#tour-enclosure-details-title',
            FORM = '#tour-enclosure-add-form',
            ERROR = '#tour-enclosure-details-error',
            NAME = '#tour-enclosure-name',
            SELECT = '.hp-select',
            SEARCHER = '#tour-enclosure-searcher',
            COLLAPSE = '#tour-enclosure-collapse',
            TOGGLE = '#tour-enclosure-toggle',
            RELATIONS = '#tour-enclosure-relations',
            RELATIONS_SEARCH = '#tour-enclosure-relations-search',
            ADD_RELATION = '#tour-enclosure-relations-add',
            ROUTE_PREFIX = '/enclosure/add';
            
        /**
         * Constructor
         */
        function EnclosureAddView() {
          
            var formStateView = new FormStateView(),
                addInProgress = false,
                addAgain = false,
                trackUri = null,
                relations = [];
          
            function reset() {
                $(NAME).val("");
                $(NAME).focus();
                formStateView.reset();
                addInProgress = false;
            }
            
            function onItemAddSuccess(task) {
                reset();
                addInProgress = false;
            }

            /**
             * @private
             */
            function onItemAddError(errorMessage) {
                addInProgress = false;
            }

            /**
             * @private
             */
            function onAddItem() {
              
                if (! addInProgress) {
                    addInProgress = true;
                    var date = new Date();
                    var item = {
                        category: 'enclosure',
                        name: $(NAME).val(),
                        uri: '/enclosure/item-' + date.getTime(),
                        date: date.toISOString()
                    };
                    presenter.addItem(item, ! addAgain, {
                        success : onItemAddSuccess,
                        error : onItemAddError
                    });
                    helpMenu.markActionDone('#/enclosure/add');

                    if (! addAgain) {
                        $(CANCEL).trigger('click');
                    }
                }

                return false;
            }
            
            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
            function onNotificationChange(notif) {
                formStateView.setMessage({
                    summary: notif.summary + ' ' + notif.sourceName,
                    status: notif.status
                });
            }
          
            /**
             * @public
             */
            this.resume = function () {
                presenter.on('notificationChange', onNotificationChange);
            };
            
            this.pause = function () {
                presenter.off('notificationChange', onNotificationChange);
                formStateView.reset();
            };
            
            this.init = function() {
              
                // add some dummy relations
                relations = [["Aunt"], ["Cousin"], ["Uncle"]];
                
                $(RELATIONS).dataTable({
                    bPaginate : false,
                    //bFilter : false,
                    bInfo : false,
                    oLanguage: {
                        sEmptyTable: localizer.getString('hpsum.node.noItemsFound'),
                        sSearch: localizer.getString('hpsum.common.search')
                    },
                    aaData: relations,
                    aoColumns: [{sTitle: "Name"}]
                });
                
                $(SELECT).selectBox({autoWidth: false});
                
                $(PANELS).hpStackedPanels({
                    panelSelector : PANEL_SELECTOR
                });
                
                var searchResults = [                    
                    {id: 1, name: "First"},
                    {id: 2, name: "Second", error: 'unavailable'},
                    {id: 3, name: "Third", help: 'help'},
                    {id: 4, name: "Fourth"},
                    {id: 5, name: "Fifth"},
                    {id: 6, name: "Sixth"},
                    {id: 7, name: "Seventh"},
                    {id: 8, name: "Eighth"}
                ];
                
                $(SEARCHER).hpSearchCombo({
                    getResults: function (string, handlers, count, start) {
                        setTimeout(function () {
                            var results = searchResults;
                            if (string && string.length > 0) {
                                results =
                                    $.grep(searchResults, function(option, index) {
                                        return (option.name.match(
                                            new RegExp(string, 'i')));
                                    });
                            }
                            handlers.success({
                                count: results.length,
                                members: results, 
                                start: 0,
                                total: results.length
                            });
                        }, 200); // simulate server delay
                    }
                });
                
                $(TOGGLE).hpToggle({checked: 'Enabled', unchecked: 'Disabled'});
                
                $(COLLAPSE).hpCollapsible();
                
                formStateView.init({form: FORM,
                    routePattern: ROUTE_PREFIX + '.*',
                    autoTrack: true});
                    
                formStateView.on('change', function () {
                    presenter.stopTracking();
                });
                
                $(ADD).on('click', function(ev) {
                    addAgain = false;
                    onAddItem.call(this);
                    ev.preventDefault();
                });
                $(ADD_AGAIN).on('click', function(ev) {
                    addAgain = true;
                    onAddItem.call(this);
                    ev.preventDefault();
                });
                $(CANCEL).bind('click', function(ev) {
                    formStateView.reset();
                });
                
                router.watch('enclosure add section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                
                this.resume();
            };
        }

        return new EnclosureAddView();
    }());
    
    return EnclosureAddView;
});
