define('bitbucket/internal/feature/ssh/keys/access/common', [
    'lodash',
    'exports'
], function(
    _,
    exports
) {

    'use strict';

    function eqKeyAccess(lhs, rhs) {
        if (lhs.key.id !== rhs.key.id) {
            return false;
        }

        if (lhs.repository) {
            return rhs.repository && rhs.repository.id === lhs.repository.id;
        } else {
            return rhs.project && rhs.project.id === lhs.project.id;
        }
    }

    function notEqKeyAccess(lhs, rhs) {
        return !eqKeyAccess(lhs, rhs);
    }

    /**
     * Searches for a key access in a collection grouped by resource type
     * @param keyAccesses keyAccesses grouped by type: { 'projects': [keyAccesses], 'repositories': [keyAccesses] }
     * @param keyAccess the key access to find
     * @returns true if found, false otherwise
     */
    function containsKeyAccess(keyAccesses, keyAccess) {
        var targetResource = keyAccess.repository ? keyAccess.repository : keyAccess.project;
        var matchingId = function (resource) { return targetResource.id === resource.id; };

        return (keyAccess.repository && _.findWhere(keyAccesses.repositories, { id : targetResource.id })) ||
            (keyAccess.project && _.findWhere(keyAccesses.projects, { id : targetResource.id }));
    }

    exports.containsKeyAccess = containsKeyAccess;
    exports.eqKeyAccess = eqKeyAccess;
    exports.notEqKeyAccess = notEqKeyAccess;
});