// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {ServerPresenter}
 */
define(['hpsum/model/server/ServerResource',
		'hpsum/model/node/NodeResource',
    '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 (serverResource, nodeResource, indexService, router, urlFragment, linkTargetBuilder,
    notifications, EventDispatcher, session, localizer) {
"use strict";

    var ServerPresenter = (function () {

        /**
         * @constructor
         */
        function ServerPresenter() {
          
            var dispatcher = new EventDispatcher();
            var selectedName = '';
            var trackUri = null;
            var initDone = false,
            	resource =null;
            
            function getItem() {
              var uris = resource.getSelection().uris;
                selectedName = '';
                if (uris && uris.length > 0) {
                    resource.getItem(uris[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 + " servers";
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
            
            this.haveItems = function () {
                return resource.haveSome();
            };
            
            this.selectionLabel = function () {
                return selectedName;
            };
            
            this.addItem = function (item, selectItem, handlers) {
                // add a task
                var task = {
                    category: 'task',
                    name: localizer.getString('hpsum.switchUI.added'),
                    uri: '/task/task-' + (new Date()).getTime(),
                    status: 'unknown',
                    changing: true,
                    sourceUri: item.uri,
                    sourceName: item.name,
                    date: item.date,
                    state: 'running',
                    progress: 10,
                    progressStep: 'Initializing',
                    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,
                    progress: task.progress,
                    step: task.progressStep
                };
                notifications.add(notif, true);
                trackUri = item.uri;
                
                item.status = 'unknown';
                indexService.addItem(item.category, item);
                
                //handlers.success(task);
                if (selectItem) {
                    resource.setSelectedUris([item.uri]);
                }
                resource.getIndexResults();
                
                if (item.uri === trackUri) {
                    dispatcher.fire('notificationChange', notif);
                }
                
                // simulate task execution
                var remaining = 100;
                var timer = setInterval(function () {
                    remaining -= 20;
                    task.progress = (100 - remaining);
                    task.progressStep = 'Committing';
                    if (remaining <= 0) {
                        clearInterval(timer);
                        
                        task.name = localizer.getString('hpsum.switchUI.added');
                        task.status = 'ok';
                        delete task['progressStep'];
                        delete task['progress'];
                        delete task['changing'];
                        
                        notif.summary = task.name;
                        notif.status = task.status;
                        delete notif.progress;
                        delete notif.step;
                        delete notif.changing;
                        notifications.add(notif, true);
                        
                        if (item.uri === trackUri) {
                            dispatcher.fire('notificationChange', notif);
                        }
                        
                        item.status = 'ok';
                        dispatcher.fire('itemChange', item);
                        var indexResult = resource.getIndexResultForUri(item.uri);
                        indexResult.status = 'ok';
                        resource.updateIndexResult(indexResult);
                    }
                }, 2000);
            };
            
            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, false);
                
                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 label = selectedName;
                indexService.getIndexForResource(resource.getSelection().uris[0], {
                    success: function (item) {
                        indexService.deleteItems(resource.getSelection().uris);
                        resource.clearAllSelectedUris(true);
                        handlers.success(label);
                        notifications.add({
                            summary: localizer.getString('hpsum.switchUI.deletedNo'),
                            sourceName: label,
                            status: 'ok'
                        });
                        router.go(urlFragment.replaceUris(router.location(), []), 'hpsum deleted server');
                    }
                });
            };
            
            this.setBIOS = function () {
                // TODO
            };
            
            this.stopTracking = function () {
                trackUri = null;
            };
            
            /**
             * @public
             */
            this.init = function() {
                var rtype = router.location().split('/');
                	rtype = rtype[1];
                	if(rtype=== 'node')
                		resource = nodeResource;
                	else 
                		resource = serverResource;
                resource.on("selectionChange", selectionChange);
                initDone = true;
            };
            
            this.resource = function () {
                return resource;
            }
            
            this.getSelection = function() {
                return resource.getSelection();
            };
            
            this.getAddLink = function () {
                var result = null;
                if (session.canPerformAction('SERVER', 'ADD')) {
                    result = linkTargetBuilder.makeLink(localizer.getString('hpsum.server.addServer'), null, 'add', 'server', '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':
                        callback(resource.getSelection());
                        break;
                    case 'itemChange':
                        uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                        	//var url = resource.getSelection().uris[0].replace(/enclosure|fc_switch|windows|linux|vmware|switch|host/, 'node');
                            resource.getItem(uris[0], {success: callback});
                         // resource.getItem(uris[0], {success: callback});
                        }
                        break;
                    case 'itemError':
                        uris = resource.getSelection().uris;
                        if (uris && uris.length === 1) {
                        	//var url = resource.getSelection().uris[0].replace(/enclosure|fc_switch|windows|linux|vmware|switch|host/, 'node');
                            resource.getItem(uris[0], {error: callback});
                       // resource.getItem(uris[0], {success: callback});
                        }
                        break;
                }
            };
 
            
            this.off = function(eventName, callback) {
                dispatcher.off(eventName, callback);
            };
        }

        return new ServerPresenter();
    }());

    return ServerPresenter;
});
