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

define(['hpsum/presenter/switch/SwitchPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/view/FormStateView',
    'hp/core/Localizer',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'lib/jquery.selectBox',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpToggle'],
function(presenter, router, urlFragment, notifications, FormStateView, localizer) { "use strict";

    var SwitchEditView = (function() {
      
        var OK = '#tour-switch-edit-ok';
        var CANCEL = '#tour-switch-edit-cancel';
        var PANEL_SELECTOR = '#tour-switch-edit-panel-selector';
        var PANELS = '#tour-switch-edit-panels';
        var TITLE = '#tour-switch-details-title';
        var FORM = '#tour-switch-edit-form';
        var NAME = '#tour-switch-name';
        var SELECT = '.hp-select';
        var SEARCHER = '#tour-switch-searcher';
        var COLLAPSE = '#tour-switch-collapse';
        var TOGGLE = '#tour-switch-toggle';
        var RELATIONS = '#tour-switch-relations';
        var RELATIONS_SEARCH = '#tour-switch-relations-search';
        var ADD_RELATION = '#tour-switch-relations-add';
        var ROUTE_PREFIX = '/switch/edit';
        
        /**
         * Constructor
         */
        function SwitchEditView() {
          
            var formStateView = new FormStateView();
            var updateInProgress = false;
            var relations = [];
            var changeCount = 0;
                
            function onItemChange(item) {
                if (item) {
                    $(TITLE).html(item.name);
                    $(NAME).val(item.name);
                } else {
                    $(TITLE).html('');
                }
                formStateView.reset();
            }
            
            function onItemError(errorMessage) {
                formStateView.noItem(errorMessage);
            }
            
            function onSelectionChange(selection) {
                urlFragment.replaceHrefUris(PANEL_SELECTOR, selection.uris);
            }
            
            function onItemUpdateSuccess(item) {
                var alertMsg = localizer.getString('hpsum.switchUI.updated') + " " + item.name;
                notifications.add({summary: localizer.getString('hpsum.switchUI.updated'), sourceName: item.name,
                    sourceUri: item.uri});
                updateInProgress = false;
                formStateView.reset();
                $(CANCEL).trigger('click');
            }

            /**
             * @private
             */
            function onItemUpdateError(errorMessage) {
                notifications.show(errorMessage);
                updateInProgress = false;
            }
            
            function onUpdateItem() {
                if (! updateInProgress) {
                    updateInProgress = true;
                    presenter.updateSelectedItems({name: $(NAME).val()}, {
                        success : onItemUpdateSuccess,
                        error : onItemUpdateError
                    });
                }
            }
            
            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }
            
            this.resume = function () {
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemChange", onItemChange);
                presenter.on("itemError", onItemError);
                changeCount = 0;
                $('.hp-toolbar-changes').hide();
            };
            
            this.pause = function () {
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
            };
          
            /**
             * @public
             */
            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
                });
                
                /*$(SEARCHER).flexbox({
                    results: [
                        {id: 1, name: "First"},
                        {id: 2, name: "Second"},
                        {id: 3, name: "Third"}
                    ]
                }, {arrowClass: 'ffb-search-icon'});*/
                
                $(TOGGLE).hpToggle({checked: 'Enabled', unchecked: 'Disabled'});
                
                $(COLLAPSE).hpCollapsible();
                
                formStateView.init({form: FORM,
                    autoTrack: true});
                
                $(OK).live('click', function(ev) {
                    onUpdateItem();
                    ev.preventDefault();
                });
                
                router.watch('switch edit section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                    
                $('input').change(function () {
                    changeCount += 1;
                    $('.hp-toolbar-changes').html(changeCount + ' modification' +
                        (changeCount > 1 ? 's' : '') +
                        ' pending').show();
                });
                
                this.resume();
            };
        }

        return new SwitchEditView();
    }());
    
    return SwitchEditView;
});
