"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const tape_1 = __importDefault(require("tape-promise/tape"));
const uuid_1 = require("uuid");
const jose_1 = require("jose");
const cactus_core_api_1 = require("@hyperledger/cactus-core-api");
const public_api_1 = require("../../../../main/typescript/public-api");
const metrics_1 = require("../../../../main/typescript/prometheus-exporter/metrics");
const public_api_2 = require("../../../../main/typescript/public-api");
const logLevel = "TRACE";
(0, tape_1.default)("can install plugin-consortium-manual", async (t) => {
    const keychainId = (0, uuid_1.v4)();
    const consortiumPluginInstanceId = (0, uuid_1.v4)();
    // Adding a new plugin to update the prometheus metric K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS
    const keyPair = await await (0, jose_1.generateKeyPair)("ES256K");
    const keyPairPem = await (0, jose_1.exportPKCS8)(keyPair.privateKey);
    const db = {
        cactusNode: [],
        consortium: [],
        consortiumMember: [],
        ledger: [],
        pluginInstance: [],
    };
    const pluginsPath = path_1.default.join(__dirname, // start at the current file's path
    "../../../../../../../", // walk back up to the project root
    ".tmp/test/cmd-api-server/plugin-import-with-npm-install_test", // the dir path from the root
    (0, uuid_1.v4)());
    const configService = new public_api_1.ConfigService();
    const apiServerOptions = await configService.newExampleConfig();
    const pluginManagerOptions = { pluginsPath };
    const pluginManagerOptionsJson = JSON.stringify(pluginManagerOptions);
    apiServerOptions.pluginManagerOptionsJson = pluginManagerOptionsJson;
    apiServerOptions.authorizationProtocol = public_api_1.AuthorizationProtocol.NONE;
    apiServerOptions.configFile = "";
    apiServerOptions.apiCorsDomainCsv = "*";
    apiServerOptions.apiPort = 0;
    apiServerOptions.cockpitPort = 0;
    apiServerOptions.grpcPort = 0;
    apiServerOptions.crpcPort = 0;
    apiServerOptions.apiTlsEnabled = false;
    apiServerOptions.plugins = [
        {
            packageName: "@hyperledger/cactus-plugin-keychain-memory",
            type: cactus_core_api_1.PluginImportType.Local,
            action: cactus_core_api_1.PluginImportAction.Install,
            options: {
                instanceId: (0, uuid_1.v4)(),
                keychainId,
                logLevel,
            },
        },
        {
            packageName: "@hyperledger/cactus-plugin-consortium-manual",
            type: cactus_core_api_1.PluginImportType.Local,
            action: cactus_core_api_1.PluginImportAction.Install,
            options: {
                instanceId: consortiumPluginInstanceId,
                keyPairPem: keyPairPem,
                consortiumDatabase: db,
            },
        },
    ];
    const config = await configService.newExampleConfigConvict(apiServerOptions);
    const apiServer = new public_api_1.ApiServer({
        config: config.getProperties(),
    });
    tape_1.default.onFinish(() => apiServer.shutdown());
    const startResponse = apiServer.start();
    await t.doesNotReject(startResponse, "started API server OK");
    t.ok(startResponse, "startResponse truthy OK");
    const addressInfoApi = (await startResponse).addressInfoApi;
    const protocol = apiServerOptions.apiTlsEnabled ? "https" : "http";
    const { address, port } = addressInfoApi;
    const apiHost = `${protocol}://${address}:${port}`;
    t.comment(`Metrics URL: ${apiHost}/api/v1/api-server/get-prometheus-exporter-metrics`);
    const apiConfig = new cactus_core_api_1.Configuration({ basePath: apiHost });
    const apiClient = new public_api_2.DefaultApi(apiConfig);
    {
        const res = await apiClient.getPrometheusMetricsV1();
        const promMetricsOutput = "# HELP " +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            " Total number of plugins imported\n" +
            "# TYPE " +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            " gauge\n" +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            '{type="' +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            '"} 2';
        t.ok(res);
        t.ok(res.data);
        t.equal(res.status, 200);
        t.true(res.data.includes(promMetricsOutput), "Total 2 plugins imported as expected. RESULT OK");
    }
    const pluginRegistry = await apiServer.getOrInitPluginRegistry();
    // this is not a working plugin but we are just testing the monitoring so
    // it's okay for this particular test case. Do not copy this to other test
    // cases or if you do remove right after you copied it ;-)
    pluginRegistry.plugins.push({});
    {
        const res = await apiClient.getPrometheusMetricsV1();
        const promMetricsOutput = "# HELP " +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            " Total number of plugins imported\n" +
            "# TYPE " +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            " gauge\n" +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            '{type="' +
            metrics_1.K_CACTUS_API_SERVER_TOTAL_PLUGIN_IMPORTS +
            '"} 3';
        t.ok(res);
        t.ok(res.data);
        t.equal(res.status, 200);
        t.true(res.data.includes(promMetricsOutput), "Total 3 plugins imported as expected. RESULT OK");
    }
    // clean up after ourselves,
    // e.g. remove the dummy plugin instance we just pushed
    pluginRegistry.plugins.pop();
    const keychain = pluginRegistry.findOneByKeychainId(keychainId);
    const hasX1 = await keychain.has("x");
    t.false(hasX1, "hasX1 === false OK");
    await keychain.set("x", "y");
    const hasX2 = await keychain.has("x");
    t.true(hasX2, "hasX2 === true OK");
    // TODO - use the new getOneById implementation once
    // https://github.com/hyperledger/cactus/issues/1197
    // has been resolved
    const consortiumPlugin = pluginRegistry
        .getPlugins()
        .find((it) => it.getInstanceId() === consortiumPluginInstanceId);
    t.ok(consortiumPlugin, "consortiumPlugin located via instance ID truthy OK");
    // FIXME - uncomment this once https://github.com/hyperledger/cactus/issues/1199
    // has been resolved (and also published to npm)
    // const nodeJwsRes = await consortiumPlugin.getNodeJws({});
    // t.ok(nodeJwsRes, "nodeJwsRes truthy OK");
    t.end();
});
//# sourceMappingURL=data:application/json;base64, 