// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {HostPresenter}
 */
define(['hpsum/model/host/HostResource',
    'hp/services/IndexService',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/LinkTargetBuilder',
    'hp/core/Notifications',
    'hp/core/EventDispatcher',
    'hp/model/Session',
    'hp/core/Localizer'], 
function(resource, indexService, router, urlFragment, linkTargetBuilder,
    notifications, EventDispatcher, session, localizer) {"use strict";

    var HostPresenter = ( function() {

        /**
         * @constructor
         */
        function HostPresenter() {
          
            var dispatcher = new EventDispatcher();
            var selectedName = '';
            
            function selectionChange(selection) {
                dispatcher.fire("selectionChange", selection);
                selectedName = '';
                if (selection.uris) {
                    if (! selection.multiSelectId) {
                        // get the selected item
                        resource.getItem(selection.uris[0], {
                            success: function (item) {
                                selectedName = item.name;
                                dispatcher.fire("itemChange", item);
                            },
                            error: function (errorMessage) {
                                dispatcher.fire("itemError", errorMessage);
                            }
                        });
                    } else {
                        // generate aggregate information
                        var aggregate = {count: selection.uris.length,
                            status:{ok: 0, warning: 0, error: 0, disabled: 0, unknown: 0}};
                        var indexResult;
                        
                        $.each(selection.uris, function(index, uri) {
                            indexResult = resource.getIndexResultForUri(uri);
                            aggregate.status[indexResult.status] += 1;
                        });
                        //selectedName = aggregate.count + " VM hosts";
                        selectedName = aggregate.count + " " + localizer.getString('hpsum.host.vmHosts');
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
            
            this.haveItems = function () {
                return resource.haveSome();
            };
            
            this.selectionLabel = function () {
                return selectedName;
            };
            
            this.addItem = function (item, handlers) {
                indexService.addItem('host', item);
                handlers.success(item);
                resource.getIndexResults();
                resource.setSelectedUris([item.uri]);
            };
            
            this.updateSelectedItems = function (item, handlers) {
                // add a task
                var task = {
                    category: 'task',
                    name: localizer.getString('hpsum.common.updating'),
                    uri: '/task/task-' + (new Date()).getTime(),
                    status: 'unknown',
                    changing: true,
                    sourceUri: resource.getSelection().uris[0],
                    sourceName: item.name,
                    date: item.date,
                    state: 'running',
                    owner: 'Somebody'
                };
                indexService.addItem('task', task);
                indexService.addItem('activity', task);
                
                var notif = {
                    summary: task.name,
                    uri: task.uri,
                    status: task.status,
                    sourceName: task.sourceName,
                    sourceUri: task.sourceUri
                };
                notifications.add(notif, true);
                
                indexService.updateItems(resource.getSelection().uris, item);
                
                handlers.success(task);
                resource.getIndexResults();
                
                var timer = setTimeout(function () {
                    task.name = localizer.getString('hpsum.switchUI.updated');
                    task.status = 'ok';
                    
                    notif.summary = task.name;
                    notif.status = task.status;
                    notifications.add(notif, true);
                }, 500);
            };
            
            this.deleteSelectedItems = function (handlers) {
                var item;
                var uris = resource.getSelection().uris;
                var label = selectedName;
                indexService.getIndexForResource(uris[0], {
                    success: function (item) {
                        indexService.deleteItems(uris);
                        resource.clearAllSelectedUris(true);
                        handlers.success(label);
                        router.go(urlFragment.replaceUris(router.location(), []), 'hpsum deleted host');
                    }
                });
            };
            
            /**
             * @public
             */
            this.init = function() {
                resource.on("selectionChange", selectionChange);
            };
            
            this.getSelection = function() {
                return resource.getSelection();
            };
            
            this.getAddLink = function () {
                var result = null;
                if (session.canPerformAction('HOST', 'ADD')) {
                    //result = linkTargetBuilder.makeLink('Add VM host', null, 'add', 'host', 'ADD');
                    result = linkTargetBuilder.makeLink(localizer.getString('hpsum.host.addVmHost'), null, 'add', 'host', 'ADD');
                }
                return result;
            };
            
            /**
             * Add a listener for a specified event.
             * @public
             * @param {string} eventName The name of the event.
             * @param {function(...)}
             */
            this.on = function(eventName, callback) {
                var uris;
                dispatcher.on(eventName, callback);
                // fire initial state
                switch (eventName) {
                    case 'selectionChange':
                        dispatcher.fire('selectionChange',
                            resource.getSelection());
                        break;
                    case 'itemChange':
                        uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                            resource.getItem(uris[0], {success: callback});
                        }
                        break;
                    case 'itemError':
                        uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                            resource.getItem(uris[0], {error: callback});
                        }
                        break;
                }
            };
            
            this.off = function(eventName, callback) {
                dispatcher.off(eventName, callback);
            };
        }

        return new HostPresenter();
    }());

    return HostPresenter;
});
