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

    var EnclosurePresenter = (function () {

        /**
         * @constructor
         */
        function EnclosurePresenter() {
          
            var dispatcher = new EventDispatcher();
            var selectedName = '';
            var initDone = false;
            var trackUri = null,
            	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);
                            if (indexResult) {
                                aggregate.status[indexResult.status] += 1;
                            }
                        });
                        selectedName = aggregate.count + " enclosures";
                        
                        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.common.adding'),
                    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('enclosure', 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';
                    task.date = (new Date()).toISOString();
                    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 enclosure');
                    }
                });
            };
            
            this.stopTracking = function () {
                trackUri = null;
            };
            
            /**
             * @public
             */
            this.init = function() {
            	var rtype = router.location().split('/');
                	rtype = rtype[1];
                	if(rtype=== 'node')
                		resource = nodeResource;
                	else 
                		resource = encResource;
                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('ENCLOSURE', 'ADD')) {
                    result = linkTargetBuilder.makeLink(localizer.getString('hpsum.enclosure.addEnclosure'), null, 'add', 'enclosure', '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 EnclosurePresenter();
    }());

    return EnclosurePresenter;
});
