// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {RackPresenter}
 */
define(['hp/services/IndexService',
    'hp/core/EventDispatcher'], 
function (indexService, EventDispatcher) {
"use strict";

    var GenericPresenter = (function () {

        /**
         * @constructor
         */
        function GenericPresenter() {
          
            var dispatcher = new EventDispatcher();
            var resource = null;
            
            function getItem() {
                var uris = resource.getSelection().uris;
                if (uris && uris.length > 0) {
                    resource.getItem(resource.getSelection().uris[0], {
                        success: function (item) {
                            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;
                        });
                        
                        dispatcher.fire("aggregateChange", aggregate);
                    }
                }
            }
            
            this.haveItems = function () {
                return resource.haveSome();
            };
            
            this.addItem = function (item, handlers) {
                indexService.addItem(item.category, item);
                
                // 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);
                
                handlers.success(item);
                resource.setSelectedUris([item.uri]);
                resource.getIndexResults();
                
                // simulate task execution
                var remaining = 100;
                var timer = setInterval(function () {
                    remaining -= 10;
                    task.progress = (100 - remaining);
                    task.progressStep = 'Committing';
                    if (remaining <= 0) {
                        clearInterval(timer);
                        task.name = "Added";
                        delete task['progressStep'];
                        delete task['progress'];
                    }
                }, 4000);
            };
            
            this.updateSelectedItems = function (item, handlers) {
                indexService.updateItems(resource.getSelection().uris, item);
                handlers.success(item);
                resource.getIndexResults();
            };
            
            this.deleteSelectedItems = function (handlers) {
                var item;
                indexService.getIndexForResource(resource.getSelection().uris[0], {
                    success: function (item) {
                        indexService.deleteItems(resource.getSelection().uris);
                        resource.clearAllSelectedUris(true);
                        handlers.success(item.name);
                        resource.getIndexResults();
                    }
                });
            };
            
            /**
             * @public
             */
            this.init = function(resourceArg) {
                resource = resourceArg;
                resource.on("selectionChange", selectionChange);
            };
            
            this.getResource = function () {
                return resource;
            };
            
            this.getSelection = function() {
                return resource.getSelection();
            };
            
            /**
             * 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 GenericPresenter;
    }());

    return GenericPresenter;
});
