// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['fs/model/activity/ActivityResource',
    'hp/services/IndexFilter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/EventDispatcher'],
function(resource, IndexFilter, router, urlFragment, EventDispatcher) {"use strict";

    var ActivityResourcePresenter = ( function() {

        var ROUTE_SUFFIX = '(/.*|$)';

        /**
         * @constructor
         * @type {ActivityPresenter}
         */
        function ActivityResourcePresenter() {

            var dispatcher = new EventDispatcher();
            var activeUri;
            var paused = true;

            function deactivate() {
                var location = router.location();
                var parameters = urlFragment.getParameters(location);
                activeUri = undefined;
                delete parameters.activityUri;
                location = urlFragment.replaceParameters(location, parameters);
                router.replaceWith(location, 'resource activity collapse');
            }

            function activate(uri) {
                var location = router.location();
                var parameters = urlFragment.getParameters(location);
                activeUri = uri;
                if (activeUri) {
                    parameters.activityUri = activeUri;
                    location = urlFragment.replaceParameters(location, parameters);
                    router.replaceWith(location, 'resource activity expand');
                }
            }

            
            function updateFilter(location) {
                var uris = urlFragment.getUris(location);                
                if (uris && uris.length > 0) {
                    var filter = new IndexFilter(resource.getIndexFilter());
                    // if we already in the right place , do nothing to avoid 
                    // unnecessary table reload
                    
                    var priorUris = filter.getHiddenProperty('associatedResourceUri');                    
                    if (!(priorUris && (priorUris[0] === uris[0] ))) {
                    
                        filter.setHiddenProperty('associatedResourceUri', uris);
                        filter.setSort('created', 'desc');
                        // Set the hidden filter properties explicitly here since
                        // resource.getIndexFilter() may be null
                        resource.initializeDefaultFilter(filter);
                        resource.setIndexFilter(filter, true);
                    }
                }
            }

            function onRouteChange(location) {
                if (!paused) {
                    var parameters = urlFragment.getParameters(location);
                    // updateFilter causes resource to dispatch a filterChange event,
                    // which causes IndexPresenter to execute resetGetResults
                    updateFilter(location);

                    if (parameters.hasOwnProperty('activityUri') &&
                        activeUri !== parameters.activityUri) {
                        activeUri = parameters.activityUri;
                        dispatcher.fire('activeUriChange', activeUri);
                    }
                }
            }

            function onIndexResultsChanged(indexResults) {
                // clear activeUri if not in the results
                if (activeUri) {
                    var length = indexResults.members.length;
                    var found = false;
                    for (var i=0; i<length; i++) {
                        if (indexResults.members[i].uri === activeUri) {
                            found = true;
                            break;
                        }
                    }
                    if (! found) {
                        deactivate();
                    }
                }
            }

            function resetFilter() {
                var filter = resource.getIndexFilter();
                if (filter) {
                    filter.resetToDefaults();
                    filter.unsetHiddenProperty('parentTaskUri');
                    filter.unsetHiddenProperty('associatedResourceUri');
                    filter.setReferenceUri(null);
                    resource.initializeDefaultFilter(filter);
                }
            }

            /**
             * @public
             */
            this.init = function (route) {
                router.watch(route + ' activity resource',
                    route + ROUTE_SUFFIX, {change: onRouteChange});
            };

            this.pause = function () {
                resource.off('indexResultsChange', onIndexResultsChanged);
                // rest filters in case the user is navigating to the Activity page,
                // which uses the same resource object.  If the filter is not cleared,
                // the Activity page will get the current Activity view filters.
                resetFilter();               
                paused = true;
            };

            this.resume = function () {
                paused = false;
                resetFilter();
                resource.on('indexResultsChange', onIndexResultsChanged);
            };

            this.resource = function () {
                return resource;
            };

            this.activate = activate;

            this.deactivate = deactivate;

            /**
             * @public
             * Add a listener for a specified event.
             * @param {string} eventName The name of the event.
             * @param {function(...)}
             */
            this.on = function (eventName, callback) {
                dispatcher.on(eventName, callback);
            };

            this.off = function (eventName, callback) {
                dispatcher.off(eventName, callback);
            };
        }

        return ActivityResourcePresenter;
    }());

    return ActivityResourcePresenter;
});
