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

define(['hp/core/Router',
    'hp/core/LinkTargetBuilder',
    'hp/services/IndexService'], 
function(router, linkTargetBuilder, indexService) {"use strict";

    var AssociatedRoute = ( function() {

        /**
         * @constructor
         * @type {AssociatedRoute}
         */
        function AssociatedRoute() {
          
            /**
             * Routes to an associated resource.
             * Used for situations where an index resource that is in the search
             * results or the map doesn't have its own top level page for that category.
             * Here, we figure out where to go by traversing the association.
             */
            this.routeToAssociated = function(associationName, uri, viewName) {
                indexService.getParentAndChildrenAssociations({
                    parentDepth: 1,
                    childDepth: 0,
                    uri: uri,
                    handlers: {
                        success: function (tree) {
                            var association = tree.parents[associationName];
                            if (association && association.length > 0) {
                                var parentUri = association[0].resource.uri;
                                var location =
                                    linkTargetBuilder.makeLocation(parentUri, viewName);
                                router.go(location, "search by association");
                            }
                        }
                    }
                });
            };
        }

        return new AssociatedRoute();
    }());

    return AssociatedRoute;
});
