All files / universal/gpii/node_modules/matchMakerFramework/src MatchMakerUtilities.js

100% Statements 215/215
89.74% Branches 70/78
100% Functions 56/56
100% Lines 214/214
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662                                        7x 7x   7x     7x 7x                   7x 7x             7x 16273x 16273x               7x 1492x     1492x 1492x   1492x                                   7x 1416x 1416x 1492x 1492x   1416x           7x 4053x 7739x 7739x 5342x     2397x                         7x 1656x 1656x 1656x                           7x 2085x 2085x 11526x 11526x 11526x 8425x     2085x                             7x 144x 589x 589x 589x   589x 589x   589x                                             7x 142x 142x   142x 162x     162x     162x   162x 162x 162x 162x 668x 234x       142x       7x 222x   222x 175x   222x                                   7x   173x 173x 720x 140x       173x   173x 62x 62x     62x 140x 140x     140x 43x       97x     504x 294x     210x   15x       97x         97x 88x 88x         9x 9x                                       7x 9x 24x 24x 24x                                           7x 334x 328x 237x 237x 97x 97x                                             7x   162x 8x 8x   8x 8x 8x             7x 162x 104x   104x 82x               7x 236x   236x     236x 236x 236x 1213x       236x 80x   400x 5x 5x           236x   2379x 774x     1605x 80x     1525x                       7x 144x       144x 164x     164x 164x 236x 236x               164x 21x     144x                         7x 148x 148x 168x 168x 110x     148x                                       7x 143x   589x 589x   589x   326x         7x 912x 912x 141x   141x 714x     141x 141x 141x   165x   111x     54x       165x 165x 165x 165x       912x                                             7x 142x 142x 662x   142x 142x 163x 163x 912x   912x     142x     7x 18x 4x 4x 4x         14x 20x 14x                           7x 12x 12x 12x 18x 14x 4x 4x 4x 4x         12x       7x                                   7x   8523x 11552x 14781x 14781x   2526x 2526x 2526x         8523x      
/*!
GPII Matchmaker Framework - Utilities
 
Copyright 2012 OCAD University
Copyright 2012 Antranig Basman
Copyright 2014 Raising the Floor - international
 
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
 
The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.
 
You may obtain a copy of the License at
https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
 
/* eslint-env browser */
/* eslint strict: ["error", "function"] */
 
var fluid = fluid || require("infusion"),
    gpii = fluid.registerNamespace("gpii");
 
(function () {
 
    "use strict";
    fluid.registerNamespace("gpii.matchMakerFramework.utils");
    fluid.registerNamespace("gpii.matchMakerFramework");
 
    /**
     * APP_SETTING_PRIORITY: the priority that an application is given if the user has application
     *    specific settings in their NP set for that application, but has no explicit priority for
     *    that application.
     * MIN_USER_PRIORITY: If an explicit priority is set by the user for an application, this is
     *    the minimum value it should have, to avoid conflicting with system generated priorities.
     */
 
    gpii.matchMakerFramework.APP_SETTING_PRIORITY = 512;
    gpii.matchMakerFramework.MIN_USER_PRIORITY = 1024;
 
 
    /**
     * extracts the capabilities from a settingshandler block based on the `capabilities` entry
     * and the inputPaths of the capabilitiesTransformations block
     */
    gpii.matchMakerFramework.utils.extractCapabilities = function (settingsHandler) {
        var capabilities = fluid.model.transform.collectInputPaths(settingsHandler.capabilitiesTransformations || {});
        return capabilities.concat(fluid.makeArray(settingsHandler.capabilities));
    };
 
    /**
     * Helper function for computeAndOntologizeCapabilitiesFromSettingsHandler. Grabs the capabilities (incl. those from the
     * capabilities transformations) for a single settings handler. Returns them in the ontology
     * provided via the transform spec
    */
    gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSettingsHandler = function (settingsHandler, transformSpec) {
        var inputPaths = gpii.matchMakerFramework.utils.extractCapabilities(settingsHandler);
 
        // Input paths are flat so need to be transformed into hierarchical
        var skel = gpii.matchMakerFramework.utils.pathsToSkeleton(inputPaths, true);
        var hskeleton = fluid.model.transformWithRules(skel, transformSpec);
 
        return gpii.matchMakerFramework.utils.computeLeaves(hskeleton);
    };
 
    /**
     * Given a solution entry, all the capabilities of that solution will be calculated based on
     * input paths in the transformations (specified in the capabilitiesTransformations block) and
     * on the list in the capabilities block of that solution. The collected capabilities will be
     * transformed via the transformspec, and the result will be an array list of el-paths in the
     * ontology transformed to.
     *
     * @param solution {Object} A single solution entry, as can be found in the solutions registry
     * @param transformSpec {Object} transformation rules to transform the input paths from the solution
     *    registry format into the format desired in the output array. If if one would like the result
     *    as a list of ISO24751 el-paths and the solutionsregistry transformations are given in
     *    the flat format, a transformation rules for 'flat' to ISO24751 should be given
     * @return {Array} An array of el-paths to all the input paths of the capabilitiesTransformations
     *    concatenated with the list given in the capabilities block of the solution entry.
    */
    gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSolution = function (solution, transformSpec) {
        var settingsHandlerBlocks = [];
        fluid.each(solution.settingsHandlers, function (handlerBlock) {
            var capabilities = gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSettingsHandler(handlerBlock, transformSpec);
            settingsHandlerBlocks = settingsHandlerBlocks.concat(capabilities);
        });
        return settingsHandlerBlocks;
    };
 
    /**
     * Helper function for gpii.matchMakerFramework.utils.computeLeaves - see description there
     */
    var computeLeavesImpl = function (model, path, paths) {
        fluid.each(model, function (value, key) {
            var newPath = fluid.pathUtil.composePath(path, key.toString());
            if (fluid.isPrimitive(value)) {
                paths.push(newPath);
            }
            else {
                computeLeavesImpl(value, newPath, paths);
            }
        });
    };
 
    /**
     * Function to extract all leaves (i.e. primitive end points) from an object. More specifically,
     * it takes a object (eg. prefs set) and finds all leaves - for each leaf found the path is
     * to an array as an el-path, one path for each leaf.
     *
     * @param model {Object} the object from which to subtract leaves
     * @return {Array} an array of el-paths, one entry for each leaf found in the object
     */
    gpii.matchMakerFramework.utils.computeLeaves = function (model) {
        var paths = [];
        computeLeavesImpl(model, "", paths);
        return paths;
    };
 
    /**
     * Given a array of el-paths, this function creates an object with a structure that includes
     * all the el-paths in the array. Each of the entries will have the value passed as parameter or
     * defaulting to {} (i.e. the empty object);
     *
     * @param paths {Array} an array of el-paths that should be present in the resulting object
     * @param value {Any} the value that should be assigned to each of the keys given in the el-path array,
     *      if no @value is given, this defaults to the empty object ({})
     * @return {Object} and object with a structure containing all the el-paths, where each path has
     *     the value given in the parameter.
     */
    gpii.matchMakerFramework.utils.pathsToSkeleton = function (paths, value) {
        var togo = {};
        for (var i = 0; i < paths.length; ++i) {
            var path = paths[i];
            var existing = fluid.get(togo, path, fluid.model.escapedGetConfig);
            if (!existing) {
                fluid.set(togo, path, value || {}, fluid.model.escapedSetConfig);
            }
        }
        return togo;
    };
 
    /**
     * Given a list of solutions, calculate the capabilities and generate a skeleton based on those.
     *
     * @param solutions {Object} list of solution entries in the same format as the solutions registry
     * @param transformSpec {Object} transformation rules to translate from the format the input paths are
     *     given in in the solutions entries' capabilitiesTransformations block, to the ontology
     *     that the skeleton should be in
     * @return {Object} an object listing the same solutions as the input payload, but where each
     *     solution block instead contains three keys: 'solution' which contains the original solution
     *     entry. 'skeleton' which contains the capabilities of the solution. 'index' which contains
     *     the solution id.
     */
    gpii.matchMakerFramework.utils.expandSolutions = function (solutions, transformSpec) {
        return fluid.transform(solutions, function (solution, solutionId) {
            var solutionIdObj = {};
            solutionIdObj["http://registry.gpii.net/applications/" + solutionId] = {};
            var transformedId = fluid.model.transformWithRules(solutionIdObj, transformSpec);
 
            var paths = gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSolution(solution, transformSpec);
            var skeleton = fluid.extend(true, {}, gpii.matchMakerFramework.utils.pathsToSkeleton(paths), transformedId);
 
            return {
                solution: solution,
                skeleton: skeleton,
                index: solutionId
            };
        });
    };
 
    /**
     * Function that takes a MM payload set as input that *includes* an entry of
     * preferences in a hierarchical format, as well as a strategy for selecting solutions
     * and a set of transformations rules between ontologies.
     *
     * @param data {Object} a match maker input payload that includes a translation of the
     *     preferences in an hierarchical ontology, keyed by 'hierarchicalPrefs'.
     * @param strategy {Function} the strategy to use to select which solutions should be configured and
     *     and launched on the system
     * @param transformSpec {Object} Transformation rules FROM the format used in the input paths of the
     *     solutions registry capability transformations TO the format in which the
     *     settings of hierarchicalPrefs in the data argument are given
     * @return {Object} An object keyed by contexts and where the values are arrays of solutions
     *     to launch in that context
     */
    gpii.matchMakerFramework.utils.disposeSolutions = function (data, strategy, transformSpec, ontologyMetadata) {
        var solrecs = gpii.matchMakerFramework.utils.expandSolutions(data.solutionsRegistryEntries, transformSpec);
        var togo = {};
        // calculate match for each of the contexts
        fluid.each(data.hierarchicalPrefs.contexts, function (context, contextId) {
            var tmpSolrecs = fluid.copy(solrecs);
            // add implicit priorities based on which applications the user has application
            // specific settings for
            gpii.matchMakerFramework.utils.addPriorityFromApplicationSettings(context.preferences, tmpSolrecs);
 
            // add users explicit application priorities to the solrecs object
            gpii.matchMakerFramework.utils.parsePriorities(context, tmpSolrecs);
 
            var leaves = gpii.matchMakerFramework.utils.computeLeaves(context.preferences);
            var disposed = strategy(leaves, tmpSolrecs, data, ontologyMetadata);
            togo[contextId] = [];
            fluid.each(disposed, function (solrec, solid) {
                if (solrec.disposition === "accept") {
                    togo[contextId].push(solid);
                }
            });
        });
        return togo;
    };
 
    // true if one of the values matches across the two arrays (ignoring the indexing)
    gpii.matchMakerFramework.utils.containsSameValue = function (arr1, arr2) {
        var obj2 = fluid.arrayToHash(arr2);
        // find match across arrays or set to false
        var found = fluid.find(arr1, function (v) {
            return obj2[v];
        }, false);
        return found;
    };
 
    /**
     * Calculate dispositions based on priorities while taking solution types into account.
     *
     * NOTE: this function will modify the solrecs object by adding, changing or removing the `disposition`,
     * `dispositionReason` and `priority` properties of a solrec[solution] entry.
     *
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function. Each entry in this object will potentially be modified by the
     *     modification/addition/deletion of the disposition, priority and/or dispositionReason.
     * @param typeInfo {Object}: contains information about the type each solution is. More precisely,
     *     the value for the key `solutionTypeMapping` is a map of <solutionType name>: <array of
     *     solutionsIds of that type> pairs. The second key, `solutionTypes` is a map of <solutionIds>
     *     with <solution types> as values.
     */
    gpii.matchMakerFramework.utils.disposeFromPriority = function (solrecs, typeInfo) {
        // sort into prioritized map, eg: { 1024: [sola, solb], 200 [solc] }
        var prioritiesMap = {};
        fluid.each(solrecs, function (sol) {
            if (sol.priority) {
                fluid.set(prioritiesMap, [sol.priority, sol.index], true);
            }
        });
        // sort priority entries desc
        var priorities = Object.keys(prioritiesMap).sort(function (a, b) { return b - a; });
        // for each priority bucket:
        for (var i = 0; i < priorities.length; i++) {
            var priority = priorities[i];
            var sols = prioritiesMap[priority];
 
            // for each solution as sol
            for (var solutionId in sols) {
                var tied = [];
                var solutionType = typeInfo.solutionTypes[solutionId];
                // if a disposition is already decided for this solution, or if priority has been
                // removed (in case of ties), ignore it.
                if (solrecs[solutionId].disposition || !solrecs[solutionId].priority) {
                    continue;
                }
                // check if there are any similar typed solution with same priority:
                // for each remaining solution as rsol
                for (var otherId in sols) {
                    // if a disposition is already decided for this solution, or if priority has been
                    // removed (in case of ties), ignore it.
                    if (otherId === solutionId || solrecs[otherId].disposition || !solrecs[otherId].priority) {
                        continue;
                    }
                    // if solutions are of equal type:
                    if (gpii.matchMakerFramework.utils.containsSameValue(solutionType, typeInfo.solutionTypes[otherId])) {
                        // since we tie with another solution, resolve by other disposal means
                        tied.push(otherId);
                    }
                }
                // before accepting a solution, make sure all solutions of that type are marked reject
                gpii.matchMakerFramework.utils.rejectFromTypes(typeInfo.solutionTypes[solutionId],
                        typeInfo.solutionTypeMapping, solrecs,
                        "Another solution of same type with higher priority was found.");
 
                // if no ties, mark the current solution as "accept"
                if (tied.length === 0) {
                    solrecs[solutionId].disposition = "accept";
                    solrecs[solutionId].dispositionReason = "Has a higher priority (" + priority +
                        ") than any solution of the same type";
                } else {
                    // if there are ties, we "unreject" all of them, removing their disposition completely
                    // so they can be tiebreaked by other disposal means (such as via the canopy)
                    tied.push(solutionId);
                    gpii.matchMakerFramework.utils.removePriorityTies(tied, solrecs);
                }
            }
        }
    };
 
    /**
     * Remove priority and dispositions from tied solutions.
     * Given a list of tied solutionID and solution records, it modifies the solution
     * records by removing all priorities, dispositions and dispositionsReasons from the tied solutions.
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param tied {Array} An array of solutionIds of tied solutions for which the disposition and
     *     priority information should be removed.
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function, but might contain priority and disposition entries for each solution.
     *     Each tied entry in this object will be modified by this function
     */
    gpii.matchMakerFramework.utils.removePriorityTies = function (tied, solrecs) {
        fluid.each(tied, function (tiedSolutionId) {
            delete solrecs[tiedSolutionId].priority;
            delete solrecs[tiedSolutionId].disposition;
            delete solrecs[tiedSolutionId].dispositionReason;
        });
    };
 
    /**
     * Rejects all solutions of a given type. This is useful for ensuring that a user does not
     * get eg. multiple versions of screenReader launched. The "solution type" is the apptology
     * type as defined in the apptology ontology - see description in "%gpii-universal/documentation/Apptology.md"
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param types {Array} An array of solution types
     * @param solutionTypeMapping {Object} A hash of solutionTypes with values being arrays of solutionIds
     *     of solutions that are of that type.
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the gpii.matchMakerFramework.utils.expandSolutions
     *     function. This object will be modified in the following way: If a solution is rejected
     *     based on its type by this function, that solution entry will have a `disposition: reject`
     *     and dispositionReason added to it.
     * @param disposeReason {String}: The reason to record for rejecting this solution. If this parameter
     *     is not provided, it will default to "Solution rejected due to its type of <type>"
     */
    gpii.matchMakerFramework.utils.rejectFromTypes = function (types, solutionTypeMapping, solrecs, disposeReason) {
        fluid.each(types, function (type) {
            for (var solutionId in solutionTypeMapping[type]) {
                var sol = solrecs[solutionId];
                if (!sol.disposition) {
                    sol.disposition = "reject";
                    sol.dispositionReason = disposeReason || "Solution rejected due to its type of " + type;
                }
            }
        });
    };
 
    /**
     * Scans the metadata block for application priorities, and for each found, the priority is added
     * to the solrecs object.
     *
     * Given the context section of an NP set, the function will search the metadata section for
     * application priorities. If this is found, the entry for that solution in the solrec object
     * will be modified by the addition of a `priority` key with the value of the user priority.
     *
     * NOTE: this function will modify the solrecs object
     *
     * @param context {Object} the contextual portion of an NP set - i.e. the part of the NP set that is
     *     inside a single context (the value for the context name key)
     * @param solrecs {Object}: a map of solution information, keyed by solution ids. This object should
     *     have a format identical to the output of the `gpii.matchMakerFramework.utils.expandSolutions`
     *     function. For each solution for which the user has an application priority, this solutions'
     *     entry in solrecs will be modified by the addition of a `priority` key.
     */
    gpii.matchMakerFramework.utils.parsePriorities = function (context, solrecs) {
        // for each entry in the metadata block:
        fluid.each(context.metadata, function (metadata) {
            Eif (metadata.type === "priority") {
                fluid.each(metadata.scope, function (applicationId) {
                    // set the priority of the application if it's part of our solrecs list:
                    var solrec = solrecs[applicationId.substr("http://registry.gpii.net/applications/".length)];
                    Eif (solrec) {
                        solrec.priority = metadata.value;
                    }
                });
            }
        });
    };
 
    gpii.matchMakerFramework.utils.addPriorityFromApplicationSettings = function (preferences, solrecs) {
        fluid.each(preferences.applications, function (value, applicationId) {
            var sol = solrecs[applicationId];
            // If solution is available on the system, and doesn't already have higher priority
            if (sol && (!sol.priority || sol.priority < gpii.matchMakerFramework.APP_SETTING_PRIORITY)) {
                sol.priority = gpii.matchMakerFramework.APP_SETTING_PRIORITY;
            }
        });
    };
 
    /**
     * Filters preferences to contain only common terms and application specific settings for the solutionId
     */
    gpii.matchMakerFramework.utils.filterPreferencesForSolution = function (solutionId, allPreferences, solutionEntry) {
        var filtered = fluid.copy(allPreferences);
 
        var applicationString = "http://registry.gpii.net/applications/" + solutionId;
 
        // find supported common terms:
        var supportedCommonArr = gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSolution(solutionEntry, { "": "" });
        var supportedCommon = {}; // create object of keys that are unescaped common term URIs and values of true
        fluid.each(supportedCommonArr, function (common) {
            fluid.set(supportedCommon, common, true, fluid.model.escapedSetConfig);
        });
 
        // move any common terms from the application block to the outer level:
        if (filtered[applicationString]) { // application block for this solution
            fluid.each(filtered[applicationString], function (value, preference) {
                // move all common terms outside application block:
                if (preference.startsWith("http://registry.gpii.net/common/")) {
                    filtered[preference] = value;
                    delete filtered[applicationString][preference];
                }
            });
        }
 
        // top level: filter everything that is not the application block and supported common terms
        return fluid.remove_if(filtered, function (value, preference) {
            // Keep preference if it is a supported common term
            if (preference.startsWith("http://registry.gpii.net/common/") && supportedCommon[preference] === true) {
                return false;
            }
            // Also leave the applicaiton specific block
            if (preference.startsWith(applicationString) === true) {
                return false;
            }
 
            return true;
        });
    };
 
    /**
     * Function to build the payload required to be the output from the matchmaker framework
     *
     * @param fullModel {Object} The full input sent to the MM
     * @param disposed {Object} Object with keys of context-ids. Each value should be an array listing
     *     the disposed solutions
     * @return {Object} The data arranged to be compatible with the required MM format
     */
    gpii.matchMakerFramework.utils.buildReturnPayload = function (fullModel, disposed) {
        var togo = {
            inferredConfiguration: {}
        };
 
        fluid.each(disposed, function (solArray, contextId) {
            togo.inferredConfiguration[contextId] = {
                applications: {}
            };
            var appBlock = togo.inferredConfiguration[contextId].applications;
            fluid.each(solArray, function (solutionId) {
                var filteredSettings = gpii.matchMakerFramework.utils.filterPreferencesForSolution(solutionId, fullModel.preferences.contexts[contextId].preferences, fullModel.solutionsRegistryEntries[solutionId]);
                appBlock[solutionId] = {
                    active: true,
                    settings:filteredSettings
                };
                // TODO: add metadata sections
            });
 
            // add conditions if they exist:
            if (fullModel.preferences.contexts[contextId].conditions) {
                togo.inferredConfiguration[contextId].conditions = fullModel.preferences.contexts[contextId].conditions;
            }
        });
        return togo;
    };
 
    /**
     * Merges a set of common term preferences with an already existing preferences set. This is
     * used when merging inferred common terms from the MM input payload with the already existing
     * common terms of the NP set. This happens for all the context blocks (for which inferred
     * common terms exist). Existing common terms take priority over the inferred terms
     *
     * @param preferences {Object} A needs and Preferences set (including the context blocks)
     * @param inferred {Object} Inferred common terms, as provided in the MM input
     * @return {Object} A copy of the preferences object with the inferred common terms merged in
     */
    gpii.matchMakerFramework.utils.addInferredCommonTerms = function (preferences, inferred) {
        var togo = fluid.copy(preferences);
        fluid.each(inferred, function (context, contextId) {
            var tcont = togo.contexts[contextId];
            fluid.each(context, function (settings) {
                tcont.preferences = fluid.extend(true, settings, tcont.preferences);
            });
        });
        return togo;
    };
 
    /**
     * Adds information about the solutions types to the payload paramater, which should be in the
     * format of an input payload for matchmakers.
     *
     * Two keys are added to the given payload:
     * `solutionTypes` is a hash of solutionId->list of the solution types it is
     * `solutionTypeMapping` is a hash of solutionType->array of solutionIds of that type
     *
     * NOTE: this function will modify the supplied `payload`
     *
     * @param payload {Object} An object with the format of a standard matchmaker input payload. At a very
     *     minimum this payload should have a `solutionRegistryEntries` key with a hashmap of
     *     (solutionID => solution registry entry) pairs. Note that this object will be modified by
     *     addition of two toplevel keys: `solutionTypes` and `solutionTypeMapping`.
     * @param transformSpec {Object} ontology transform spec translating from common terms into
     *     a solution type ontology.
     */
    gpii.matchMakerFramework.utils.addSolutionTypeInformation = function (payload, transformSpec) {
        fluid.each(payload.solutionsRegistryEntries, function (entry, entryId) {
            // first get an array of what solution types the current entry is:
            var solutionTypes = gpii.matchMakerFramework.utils.computeAndOntologizeCapabilitiesFromSolution(entry, transformSpec);
            fluid.set(payload, [ "solutionTypes", entryId], solutionTypes);
            // now add solution ID to the return array in the appropriate places:
            for (var i in solutionTypes) {
                // add solution ID to the solution type
                fluid.set(payload, ["solutionTypeMapping", solutionTypes[i], entryId], true);
            }
        });
    };
 
    gpii.matchMakerFramework.utils.inferCommonTermsFromApplicationsPrefs = function (prefsId, prefsBlock, flattenedSolutionsRegistry) {
        var togo = {};
        if (prefsId.startsWith("http://registry.gpii.net/applications/")) {
            var solutionId = prefsId.substring("http://registry.gpii.net/applications/".length);
            // add any common terms from the application block directly as inferred:
            togo[solutionId] = fluid.remove_if(fluid.copy(prefsBlock), function (val, key) {
                return (!key.startsWith("http://registry.gpii.net/common/")); // keep if it's a common term
            });
            // transform the application specific settings and add them to inferred list
            Eif (solutionId in flattenedSolutionsRegistry) {
                var entry = flattenedSolutionsRegistry[solutionId];
                fluid.each(entry.settingsHandlers, function (handler) {
                    var inverseRules;
                    if (handler.inverseCapabilitiesTransformations !== undefined) {
                        // use explicit inverses if available
                        inverseRules = handler.inverseCapabilitiesTransformations;
                    } else {
                        // else fall back to using the framework's automatic inversion features
                        inverseRules = handler.capabilitiesTransformations !== undefined ?
                            fluid.model.transform.invertConfiguration(handler.capabilitiesTransformations) : {};
                    }
 
                    var transformed = fluid.model.transformWithRules(prefsBlock, inverseRules);
                    var out = {};
                    fluid.set(out, [solutionId], transformed);
                    fluid.extend(true, togo, out);
                });
            }
        }
        return togo;
    };
 
    /**
     * Converts application specific settings into common terms, keyed by application ids. Given a
     * set of preferences, for each application block in those preferences, the settings for which
     * inverse transformations exist will be transformed into common terms. All the common terms
     * that have successfully been inferred from an application will be written to a block keyed by
     * that application's ID.
     *
     * Note that we're fetching the solution registry for all platforms. The reason is that if the
     * user has e.g. application specific preferences for a Linux solution, we need that solution
     * registry entry to be able to infer common terms - even if the user is currently on a Windows
     * platform. We could consider loading specific application entries as needed - this is
     * described in GPII-2140.
     *
     * @param preferences {Object} - An NP set (including contexts, etc)
     * @param fullSolutionsRegistry {Object} - The solutionsRegistries, keyed by OS
     *
     * @return {Object} - Object whose keys are solution IDs and entries are common term
     *      preferences which have been transformed from application specific settings for that
     *      solution
     */
    gpii.matchMakerFramework.utils.inferCommonTerms = function (preferences, fullSolutionsRegistry) {
        var flattenedSolutionsRegistry = {};
        fluid.each(fullSolutionsRegistry, function (entry) {
            fluid.extend(flattenedSolutionsRegistry, entry);
        });
        var togo = {};
        fluid.each(preferences.contexts, function (context, contextId) {
            togo[contextId] = {};
            fluid.each(context.preferences, function (prefsBlock, prefsId) {
                var inferred = gpii.matchMakerFramework.utils.inferCommonTermsFromApplicationsPrefs(
                    prefsId, prefsBlock, flattenedSolutionsRegistry);
                fluid.extend(true, togo[contextId], inferred);
            });
        });
        return togo;
    };
 
    gpii.matchMakerFramework.utils.updateSingleInferredConfiguration = function (inferredConfiguration, context, pref, value, solutionId) {
        if (solutionId) {
            var path = [ context, "applications", solutionId, "settings", pref ];
            Eif (fluid.get(inferredConfiguration, path) !== undefined) {
                fluid.set(inferredConfiguration, path, value);
            }
        } else {
            // if solutionId is not provided, loop through all solutions and update the preference value
            // (if the preference is already set in the solution)
            fluid.each(inferredConfiguration[context].applications, function (sol) {
                if (sol.settings[pref] !== undefined) {
                    sol.settings[pref] = value;
                }
            });
        }
    };
 
    /**
     * Takes a set of preferences and runs through the inferredConfiguration, updating all instances
     * matching preferences/settings within the application with the new values from the preferences
     * set.
     *
     * This feature is required by the PCP to allow updating e.g. a top-level common term and
     * ensuring that the relevant applications are affected by it
     */
    gpii.matchMakerFramework.utils.updateInferredConfiguration = function (preferences, inferredConfiguration) {
        var inferred = fluid.copy(inferredConfiguration);
        fluid.each(preferences.contexts, function (contextBlock, contextName) {
            fluid.each(contextBlock.preferences, function (val, pref) {
                if (pref.startsWith("http://registry.gpii.net/common/")) {
                    gpii.matchMakerFramework.utils.updateSingleInferredConfiguration(inferred, contextName, pref, val);
                } else Eif (pref.startsWith("http://registry.gpii.net/applications/")) {
                    var solutionId = pref.substring("http://registry.gpii.net/applications/".length);
                    fluid.each(val, function (solPrefVal, solPref) {
                        gpii.matchMakerFramework.utils.updateSingleInferredConfiguration(inferred, contextName, solPref, solPrefVal, solutionId);
                    });
                }
            });
        });
        return inferred;
    };
 
 
    gpii.matchMakerFramework.utils.livenessOrdering = [
        "OSRestart",
        "manualRestart",
        "liveRestart",
        "live"
    ];
 
    /**
     * Given a term and one or more solutions registry entries, this function will walk each
     * solution (and its settingshandlers) and find the lowest liveness for any solution that
     * supports the term via its capabilities and/or capabilitiesTransformations. The lowest or least
     * liveness is dictated by gpii.matchMakerFramework.utils.livenessOrdering, where a lower
     * index means less/lower liveness.
     *
     * @param term {String}: the term to find the liveness for
     * @param solutions {Array or Object} A list of the solutions that should be search for support of the term
     * @return {String} returns the lowest/least liveness found by any solution provided that supports the term
     */
    gpii.matchMakerFramework.utils.getLeastLiveness = function (term, solutions) {
        var leastLiveness;
        fluid.each(solutions, function (solution) {
            fluid.each(solution.settingsHandlers, function (handler) {
                var capabilities = gpii.matchMakerFramework.utils.extractCapabilities(handler);
                if (capabilities && capabilities.indexOf(fluid.pathUtil.composeSegments(term)) > -1) {
                    // if the liveness of term in current solution is lower than any previously checked solutions
                    var livenessOrder = gpii.matchMakerFramework.utils.livenessOrdering.indexOf(handler.liveness);
                    Eif (leastLiveness === undefined || livenessOrder < leastLiveness) {
                        leastLiveness = livenessOrder;
                    }
                }
            });
        });
        return gpii.matchMakerFramework.utils.livenessOrdering[leastLiveness];
    };
})();