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

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

    var EnclosureShowView = (function() {
      
        var VIEW = '#tour-enclosure-show';
        var SELECTOR = '#tour-enclosure-panel-selector';
        var HEADER = '#tour-enclosure-show .hp-details-header';
        var TITLE = '#tour-enclosure-details-title';
        var STATUS = '#tour-enclosure-details-status';
        var ACTIONS = '.hp-details-actions';
        var JUMP_ACTION = '#tour-enclosure-jump-action';
        var DELETE_ACTION = '#tour-enclosure-delete-action';
        var DELETE_TITLE = '#tour-enclosure-delete-title';
        var DEPENDENCY_HEADER = '#tour-enclosure-dependency-header';
        var NOTIFY_STATUSES = {error:'error', warning:'warning', unknown:'info'};
      
        /**
         * Constructor
         */
        function EnclosureShowView() {
          
            var detailsShowView = new DetailsShowView();
            var notificationsView = new NotificationsView();
            var deleteInProgress = false;
            var notificationsCleared = false;
                
            function clearNotifications() {
                if (! notificationsCleared) {
                    notificationsCleared = true;
                    notificationsView.clear();
                }
            }
            
            function onItemChange(item) {
                clearNotifications();
                if (item) {
                    $(HEADER).removeClass('hp-show-changing');
                    $(ACTIONS).removeClass('hp-disabled');
                    $(TITLE).text(item.name).removeClass('hp-unavailable');
                    $(STATUS).hpStatus(item.status, item.changing).
                        removeClass('hp-unavailable');
                    if (item.stateDetails) {
                        notificationsView.add({
                            status: NOTIFY_STATUSES[item.status],
                            summary: item.stateDetails.summary,
                            timestamp: item.updatedAt,
                            details: item.stateDetails.details
                        });
                    }
                } else {
                    $(TITLE).text('');
                    $(STATUS).hpStatus('unknown');
                    $(STATUS + ' span').text('');
                }
            }

            function onItemError(errorMessage) {
            }
            
            function onSelectionChange(selection) {
                notificationsCleared = false;
                clearNotifications();
                urlFragment.replaceHrefUris(HEADER,
                    selection.uris, selection.multiSelectId);
                if ($(HEADER).hasClass('hp-show-init')) {
                    $(HEADER).removeClass('hp-show-init');
                } else {
                    $(HEADER).addClass('hp-show-changing');
                    $(ACTIONS).addClass('hp-disabled');
                }
            }
            
            function onAggregateChange(aggregate) {
                $(TITLE).text(aggregate.count + " Enclosures");
                $(STATUS).hide();
                notificationsCleared = false;
                clearNotifications();
            }
            
            function onItemDeleteSuccess(item_name) {
                notificationsView.add({summary: "Deleted"}, true);
                deleteInProgress = false;
            }

            /**
             * @private
             */
            function onItemDeleteError(errorMessage) {
                notificationsView.add({summary:errorMessage}, true);
                deleteInProgress = false;
            }

            /**
             * @private
             */
            function onDeleteItem(ev) {
                if (! deleteInProgress) {
                    deleteInProgress = true;
                    
                    var contents = $(deleteConfirmHtml);
                    localizer.localizeDom(contents);
                    $(DELETE_TITLE, contents).text(
                        localizer.getString('hpsum.common.deleteArg',
                            [presenter.selectionLabel()]));
                    $('.hp-collapsible', contents).hpCollapsible();
                    $(DEPENDENCY_HEADER, contents).text(
                        localizer.getString('hpsum.common.dependencyHeader',
                            [88, presenter.selectionLabel()]));
                    for (var i=1; i<=88; i+= 1) {
                        $('.hp-dependencies', contents).
                            append('<li>item ' + i + '</li>');
                    }
                    
                    var dialogView = new DialogView();
                    dialogView.init({contents: contents,
                        ok: function () {
                            if (presenter.selectionLabel() === 'server 10') {
                                return false;
                            } else {
                                presenter.deleteSelectedItems({
                                    success : onItemDeleteSuccess,
                                    error : onItemDeleteError
                                });
                            }
                        },
                        cancel: function () {
                            deleteInProgress = false;
                        }
                    });
                }
                
                ev.preventDefault();
            }
            
            var notifToggle = false;
            function onJumpAction(ev) {
                var notif = {
                    summary: "Jump",
                    status: "warning",
                    uri: 'jumper-' + presenter.selectionLabel(),
                    timestamp: (new Date()).toISOString(),
                    details: "We just added this so we could see it.",
                    sourceUri: presenter.getSelection().uris[0],
                    sourceName: presenter.selectionLabel(),
                    actions: ['<a href="#/enclosure/fly">Fly away</a>',
                        '<a href="#/enclosure/dance">Dance</a>'],
                    dismiss: function (notif) {
                        //console.log('Dismissed ' + notif.summary);
                    }
                };
                if (presenter.selectionLabel() === 'enclosure 10') {
                    notif.summary = "Jumped a long ways away to be long";
                    if (notifToggle) {
                        notificationsView.remove({uri: notif.uri});
                        notifToggle = false;
                    } else {
                        notificationsView.add(notif, true, true, true);
                        notifToggle = true;
                    }
                } else {
                    notificationsView.add(notif, true, true, true);
                }
                
                ev.preventDefault();
            }
            
            this.resume = function () {
                notificationsCleared = false;
                presenter.on("selectionChange", onSelectionChange);
                presenter.on("aggregateChange", onAggregateChange);
                presenter.on("itemChange", onItemChange);
                presenter.on("itemError", onItemError);
                notificationsView.resume();
            };
            
            this.pause = function () {
                notificationsView.pause();
                presenter.off("selectionChange", onSelectionChange);
                presenter.off("aggregateChange", onAggregateChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
            };
          
            /**
             * @public
             */
            this.init = function() {
                
                detailsShowView.init($(SELECTOR));
                notificationsView.init({context: $(VIEW),
                    allLocation: '#/enclosure/show/activity',
                    resource: presenter.resource()});
      
                $(ACTIONS).hpDropMenu();
                
                $(DELETE_ACTION).bind('click', onDeleteItem);
                $(JUMP_ACTION).bind('click', onJumpAction);
                
                this.resume();
            };
            
        }

        return new EnclosureShowView();
    }());
    
    return EnclosureShowView;
});
