// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {RackPresenter}
 */
define(['hpsum/model/switch/SwitchResource',
	'hpsum/model/node/NodeResource',
    'hp/services/IndexService',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/LinkTargetBuilder',
    'hp/core/EventDispatcher',
    'hp/model/Session',
    'hp/core/Localizer'], 
function(switchResource, nodeResource, indexService, router, urlFragment,linkTargetBuilder, EventDispatcher, session, localizer) {"use strict";

    var SwitchPresenter = ( function() {

        /**
         * @constructor
         */
        function SwitchPresenter() {
          
            var dispatcher = new EventDispatcher();
            var selectedName = '';
            var initDone = false,
            	resource =null;
            
            function getItem() {
                var uris = resource.getSelection().uris;
                selectedName = '';
                if (uris && uris.length > 0) {
                    resource.getItem(resource.getSelection().uris[0], {
                        success: function (item) {
                            selectedName = item.name;
                            dispatcher.fire("itemChange", item);
                        },
                        error: function (errorMessage) {
                            dispatcher.fire("itemError", errorMessage);
                        }
                    });
                }
            }
            
            function getAssociations() {
                var uris = resource.getSelection().uris;
                if (uris && uris.length > 0) {
                    indexService.getParentAndChildrenAssociations({
                        uri: uris[0],
                        parentDepth: 1,
                        childDepth: 1,
                        handlers: {
                            success: function (tree) {
                                dispatcher.fire("associationsChange", tree);
                            },
                            error: function (errorMessage) {
                                dispatcher.fire("associationsError", errorMessage);
                            }}
                    });
                }
            }
            
            function selectionChange(selection) {
                dispatcher.fire("selectionChange", selection);
                if (selection.uris) {
                    if (! selection.multiSelectId) {
                        // get the selected item
                        getItem();
                        getAssociations();
                    } 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 + " switches";
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
            
            this.haveItems = function () {
                return resource.haveSome();
            };
            
            this.selectionLabel = function () {
                return selectedName;
            };
            
            this.addItem = function (item, handlers) {
                resource.addItem(item, handlers);
            };
            
            this.updateSelectedItems = function (item, handlers) {
                indexService.updateItems(resource.getSelection().uris, item);
                handlers.success(item);
                resource.getIndexResults();
            };
            
            this.deleteSelectedItems = function (handlers) {
                resource.deleteItems(resource.getSelection().uris, {
                    success: function (name) {
                        handlers.success(name);
                    },
                    error: handlers.error
                });
            };
            
            /**
             * @public
             */
            this.init = function() {
           		var rtype = router.location().split('/');
                	rtype = rtype[1];
                	if(rtype=== 'node')
                		resource = nodeResource;
                	else 
                		resource = switchResource;
                resource.on("selectionChange", selectionChange);
                initDone = true;
            };
            
            this.getSelection = function() {
                return resource.getSelection();
            };
            
            this.getAddLink = function () {
                var result = null;
                if (session.canPerformAction('SWITCH', 'ADD')) {
                    result = linkTargetBuilder.makeLink(localizer.getString('hpsum.switchUI.addSwitch'), null, 'add', 'switch', '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':
                        getItem();
                        break;
                    case 'associationsChange':
                        getAssociations();
                        break;
                }
            };
            
            this.off = function(eventName, callback) {
                dispatcher.off(eventName, callback);
            };
        }

        return new SwitchPresenter();
    }());

    return SwitchPresenter;
});
