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

define(['hpsum/presenter/switch/SwitchPresenter',
    'hpsum/presenter/alerts/AlertsPresenter',
    'hp/view/DetailsShowView',
    'hp/view/DialogView',
    'hp/core/UrlFragment',
    'hp/view/NotificationsView',
    'hp/core/Localizer',
    'text!hpsumpages/server/delete_confirm.html',
    'jquery',
    'hp/lib/jquery.hpDropMenu',
    'hp/lib/jquery.hpStatus',],
function(presenter, AlertsPresenter, DetailsShowView, DialogView, urlFragment, NotificationsView, localizer, deleteConfirmHtml) { "use strict";

    var SwitchShowView = (function() {
      
        var VIEW = '#tour-switch-show',
            SELECTOR = '#tour-switch-panel-selector',
            HEADER = '#tour-switch-show .hp-details-header',
            TITLE = '#tour-switch-details-title',
            STATUS = '#tour-switch-details-status',
            INVALID_ACTION = '#tour-switch-invalid-action',
            DELETE_ACTION = '#tour-switch-delete-action',
            DELETE_NAME = '#tour-switch-delete-name',
            NOTIFY_STATUSES = {error:'error', warning:'warning', ok:'ok'};
      
        /**
         * Constructor
         */
        function SwitchShowView() {
          
            var detailsShowView = new DetailsShowView(),
                notificationsView = new NotificationsView(),
                alertsPresenter = new AlertsPresenter(),
                deleteInProgress = false,
                currentActivity = null,
                okMessage = null,
                warningMessage = null,
                errorMessage = null,
                notificationsCleared = false;
                
            function clearNotifications() {
                if (! notificationsCleared) {
                    notificationsCleared = true;
                    notificationsView.clear();
                }
            }
            
            function onItemChange(item) {
                clearNotifications();
                
                if (item) {
                    $(TITLE).html(item.name);
                    $(STATUS).hpStatus(item.status, item.changing);
                    if (NOTIFY_STATUSES[item.status]) {
                        notificationsView.add({
                            status: NOTIFY_STATUSES[item.status],
                            summary: 'Update properties',
                            timestamp: (new Date().toISOString()),
                            sourceName: item.name,
                            sourceUri: item.uri,
                            changing: item.changing,
                            progress: 25,
                            step: 'bios ROM flash',
                            details: localizer.getString('hpsum.switchUI.hasStatus', [item.name, item.status]) +
                              '<br/>' + localizer.getString('hpsum.switchUI.weHaveNoIdeaWhy') + '<br/>' +
                              localizer.getString('hpsum.switchUI.toFixIt', ['<a>' + localizer.getString('hpsum.switchUI.doThis') + '</a>.'])
                        });
                    }
                    $(DELETE_NAME).html(item.name);
                } else {
                    $(TITLE).html('');
                    $(STATUS).hpStatus('unknown');
                    $(STATUS + ' span').html('');
                }
            }

            function onItemError(errorMessage) {
            }
            
            function onAggregateChange(aggregate) {
                $(TITLE).html(aggregate.count + " " + localizer.getString('hpsum.common.switches'));
                $(STATUS).hide();
                notificationsCleared = false;
                clearNotifications();
            }
            
            function onSelectionChange(selection) {
                notificationsCleared = false;
                urlFragment.replaceHrefUris(HEADER,
                    selection.uris, selection.multiSelectId);
            }
            
            function onAlertsIndexResultsChange(indexResults) {
                clearNotifications();
                $.each(indexResults.members.reverse(), function (index, alert) {
                    notificationsView.add({
                        uri: alert.uri,
                        status: alert.status,
                        summary: alert.name,
                        timestamp: alert.date,
                        sourceName: alert.sourceName,
                        sourceUri: alert.sourceUri
                    });
                });
            }
            
            function onItemDeleteSuccess(item_name) {
                notifications.show(localizer.getString('hpsum.switchUI.deleted', [item_name]));
                deleteInProgress = false;
            }

            /**
             * @private
             */
            function onItemDeleteError(errorMessage) {
                notifications.show(errorMessage);
                // real product code should also ensure hp-details-notify
                // is populated via item state
                deleteInProgress = false;
            }

            /**
             * @private
             */
            function onDeleteItem(ev) {
                if (! deleteInProgress) {
                    deleteInProgress = true;
                    
                    var contents = $(deleteConfirmHtml);
                    $(DELETE_NAME, contents).text(presenter.selectionLabel());
                    
                    var dialogView = new DialogView();
                    dialogView.init({contents: contents,
                        ok: function () {
                            presenter.deleteSelectedItems({
                                success : onItemDeleteSuccess,
                                error : onItemDeleteError
                            })
                        },
                        cancel: function () {
                            deleteInProgress = false;
                        }
                    });
                }
                
                ev.preventDefault();
            }
          
            /**
             * @public
             */
            this.pause = function () {
                notificationsCleared = false;
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
                presenter.off("aggregateChange", onAggregateChange);
            };
            
            this.resume = function () {
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemChange", onItemChange);
                presenter.on("itemError", onItemError);
                presenter.on("aggregateChange", onAggregateChange);
            };
            
            this.init = function() {
                var deleteConfirmButtons = {};
                
                detailsShowView.init($(SELECTOR));
                notificationsView.init($(VIEW), '#/switch/show/alerts');
                $('.hp-details-actions').hpDropMenu();
                            
                $(DELETE_ACTION).bind('click', onDeleteItem);
                
                this.resume();
            };
            
        }

        return new SwitchShowView();
    }());
    
    return SwitchShowView;
});
