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

define(['hpsum/model/host/HostResource',
    'hp/view/MasterListView',
    'hpsum/presenter/host/HostPresenter',
    'hpsum/presenter/activity/ActivityPresenter',
    'hp/core/UrlFragment',
    'hp/view/DialogView',
    'hp/view/NotificationsView',
    'hp/core/Notifications',
    'text!hpsumpages/host/delete_confirm.html',
    'hp/core/Localizer',
    'jquery',
    'hp/lib/jquery.hpSafeClone',
    'hp/lib/jquery.hpDropMenu',
    'hp/lib/jquery.hpSelect',
    'hp/lib/jquery.hpStatus',
    'hp/lib/jquery.hpUtilizationMeter',],
function(resource, MasterListView, presenter, ActivityPresenter, urlFragment, DialogView, NotificationsView, notifications, deleteConfirmHtml, localizer) { "use strict";

    var HostView = (function() {
      
        var TYPE = 'host';
        var PAGE = '#tour-host-page';
        var HEADER = PAGE + ' .hp-master-header';
        var DELETE_ACTION = '#tour-host-delete-action';
        var DELETE_NAME = '#tour-host-delete-name';
      
        /**
         * Constructor
         */
        function HostView() {
          
            var masterListView = new MasterListView();
            var notificationsView = new NotificationsView();
            var activityPresenter = new ActivityPresenter();
            var template = null;
            var deleteInProgress = false;
            
            function onSelectionChange(selection) {
                $('.hp-header-selection').
                    html((selection.uris ? selection.uris.length : 0) + ' selected');
                urlFragment.replaceHrefUris(HEADER,
                    selection.uris, selection.multiSelectId);
                //activityPresenter.setSourceUris(selection.uris);
            }
            
            function onActivityIndexResultsChange(indexResults) {
                $.each(indexResults.members.slice(0).reverse(), function (index, activity) {
                    if ('alert' === activity.category) {
                        if ('ok' !== activity.status &&
                            'active' === activity.state) {
                            notificationsView.add({
                                uri: activity.uri,
                                status: activity.status,
                                summary: activity.name,
                                timestamp: activity.date,
                                sourceName: activity.sourceName,
                                sourceUri: activity.sourceUri
                            });
                        } else {
                            notificationsView.remove({uri: activity.uri});
                        }
                    } else if ('task' === activity.category) {
                        var now = new Date();
                        var date = Date.parseISOString(activity.date);
                        // build details of history
                        var history = null;
                        if (activity.history) {
                            history = '<label>' + localizer.getString('hpsum.host.history') + '</label><ol>';
                            $.each(activity.history, function (i2, hist) {
                                history += '<li>' + hist.date + ' ' +
                                    hist.step + '</li>';
                            });
                            history += '</ol>';
                        }
                        
                        if (activity.changing || 'ok' !== activity.status ||
                            date.getTime() > (now.getTime() - (1000 * 30))) {
                            notificationsView.add({
                                uri: activity.uri,
                                status: activity.status,
                                changing: activity.changing,
                                summary: activity.name,
                                timestamp: activity.date,
                                sourceName: activity.sourceName,
                                sourceUri: activity.sourceUri,
                                progress: activity.progress,
                                step: activity.progressStep,
                                details: history
                            });
                        } else {
                            notificationsView.remove({uri: activity.uri});
                        }
                    }
                });
            }
          
            function renderer(indexResult) {
                var item = template.hpSafeClone();
                $('header > .hp-status', item).
                    hpStatus(indexResult.status, indexResult.changing);
                $('.hp-master-item-name', item).html(indexResult.name);
                $('.hp-meter', item).hpUtilizationMeter();
                $('.hp-meter', item).hpUtilizationMeter(88, 0, 100);
                return item;
            }
            
            function onItemDeleteSuccess(selectionLabel) {
                notifications.add({
                    summary: localizer.getString('hpsum.switchUI.deletedNo'),
                    sourceName: selectionLabel,
                    status: 'ok'
                });
                deleteInProgress = false;
            }

            function onItemDeleteError(errorMessage) {
                notifications.show(errorMessage);
                deleteInProgress = false;
            }

            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 () {
                activityPresenter.pause();
                presenter.off('selectionChange', onSelectionChange);
                activityPresenter.off('indexResultsChange',
                    onActivityIndexResultsChange);
                masterListView.pause();
            };
            
            this.resume = function () {
                presenter.on('selectionChange', onSelectionChange);
                masterListView.resume();
                /*activityPresenter.on('indexResultsChange',
                    onActivityIndexResultsChange);
                activityPresenter.setDefaultFilters();
                activityPresenter.resume();*/
            };
            
            this.init = function () {
                
                presenter.init();
                
                template = $('#tour-host-item-template').detach().show().attr('id', '');

                $('.hp-details-actions').hpDropMenu();
              
                masterListView.init({
                    routePrefix: '/' + TYPE,
                    resource: resource,
                    page: $(PAGE),
                    multiSelect: true,
                    addLink: presenter.getAddLink(),
                    listItemRenderer: renderer
                });
                notificationsView.init($(PAGE + ' .hp-master-full'));
                
                activityPresenter.init();
                
                $(DELETE_ACTION).bind('click', onDeleteItem);
                
                this.resume();
            };
        }

        return new HostView();
    }());
    
    return HostView;
});
