/**
 *  ---------
 * |.##> <##.|  SmartCard-HSM Support Scripts
 * |#       #|
 * |#       #|  Copyright (c) 2011-2012 CardContact Software & System Consulting
 * |'##> <##'|  Andreas Schwier, 32429 Minden, Germany (www.cardcontact.de)
 *  ---------
 *
 * Consult your license package for usage terms and conditions.
 *
 * @fileoverview A registry of backend services
 */

var PKIAPIConnector = require('scsh/srv-cc1/PKIAPIConnector').PKIAPIConnector;


function BackendRegistry(service) {
    this.service = service;
    this.registry = [];
    this.map = {};
}

exports.BackendRegistry = BackendRegistry;



/**
 * Add a backend service to the registry
 *
 * @param {Object} desc a descriptor with the properties id, name, apiURL and hasHSMService
 */
BackendRegistry.prototype.addService = function(desc) {
    assert(desc.id, "Property id must be set");
    assert(desc.name, "Property name must be set");
    assert(desc.apiURL, "Property apiurl must be set");

    if (this.map[desc.id] != undefined) {
        throw new GPError(module.id, GPError.INVALID_DATA, 0, "Backend service " + desc.id + " already registered");
    }

    this.registry.push(desc);
    this.map[desc.id.toLowerCase()] = desc;
}



/**
 * Get backend service from  registry
 *
 * @param {String} id the service identifier
 * @type Object
 * @return the service description
 */
BackendRegistry.prototype.getService = function(id) {
    var desc = this.map[id.toLowerCase()];
    if (desc == undefined) {
        throw new GPError(module.id, GPError.INVALID_DATA, 0, "Backend service " + id + " not found");
    }
    return desc;
}



/**
 * Query the status of a HSM connected to the backend.
 *
 * @param {String} lastSeenAt the id of the system to which the token connected last time
 * @param {Number} subjectId the id of the subject whose tokens are queried
 * @param {Number} userId the user acting
 * @param {Number} tokenId the token to look for
 * @type Object
 * @return the token information returned from the API.
 */
BackendRegistry.prototype.queryHSMStatus = function(lastSeenAt, subjectId, userId, tokenId) {
    if (!lastSeenAt) {
        return;
    }

    var desc = this.map[lastSeenAt.toLowerCase()];
    if (!desc) {
        GPSystem.log(GPSystem.ERROR, module.id, "Unknown backend " + lastSeenAt);
        return;
    }

    try {
        var api = new PKIAPIConnector(desc);
        var token = api.getToken(subjectId, tokenId, userId);
        token.api = api;
        return token;
    }
    catch(e) {
        GPSystem.log(GPSystem.ERROR, module.id, "Could not connect to backend: " + e.message);
    }
    return;
}
