"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EthereumProofPointIssuer = void 0;
var canonicalize_1 = __importDefault(require("canonicalize"));
var localISOdt = require("local-iso-dt");
var ethereumAddressResolver_1 = require("./ethereumAddressResolver");
var ethereumProofPointRegistry_1 = require("./ethereumProofPointRegistry");
var ethereumProofPointRegistryRoot_1 = require("./ethereumProofPointRegistryRoot");
var httpClient_1 = require("../httpClient");
var ipfsStorageProvider_1 = require("../ipfs/ipfsStorageProvider");
var proofPointId_1 = require("../proofPointId");
/**
 * Ethereum Proof Point Issuer
 * Can issue, commit and revoke Proof Points in an @EthereumProofPointRegistry
 */
var EthereumProofPointIssuer = /** @class */ (function () {
    /**
     * Creates an instance of @EthereumProofPointIssuer
     * @param rootAddress The Ethereum address of the deployed eternal storage contract.
     * @param ethereumAddressResolver A resolver used to resolve issuer IDs to Ethereum addresses.
     * @param storage A storage provider used for storing and retrieving proof point documents.
     * @param registry The @EthereumProofPointRegistry used to issue, commit and revoke.
     */
    function EthereumProofPointIssuer(rootAddress, ethereumAddressResolver, storage, registry) {
        this._rootAddress = rootAddress;
        this._ethereumAddressResolver = ethereumAddressResolver;
        this._storage = storage;
        this._registry = registry;
    }
    /**
     * Constructs an @EthereumProofPointIssuer set up for production use.
     * @param rootAddress the Ethereum address of the deployed eternal storage contract.
     * @param ipfsSettings Connection settings for the IPFS node to use for storage.
     * @param ethereumProvider An Ethereum provider to use for Ethereum interactions.
     * @param registryAddress Optional, if provided will be used as the registry address, meaning
     * the address will not be looked up in the storage contract, saving one Ethereum call.
     * @returns a ready to use @EthereumProofPointIssuer
     */
    EthereumProofPointIssuer.init = function (rootAddress, ipfsSettings, ethereumProvider, registryAddress) {
        return __awaiter(this, void 0, void 0, function () {
            var registryRoot, registry, _a, httpClient, ethereumAddressResolver, storageProvider;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        registryRoot = new ethereumProofPointRegistryRoot_1.EthereumProofPointRegistryRoot(rootAddress, ethereumProvider);
                        if (!registryAddress) return [3 /*break*/, 1];
                        _a = new ethereumProofPointRegistry_1.EthereumProofPointRegistry(rootAddress, registryAddress, ethereumProvider);
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, registryRoot.getRegistry()];
                    case 2:
                        _a = _b.sent();
                        _b.label = 3;
                    case 3:
                        registry = _a;
                        httpClient = new httpClient_1.RealHttpClient();
                        ethereumAddressResolver = new ethereumAddressResolver_1.EthereumAddressResolver(httpClient);
                        storageProvider = new ipfsStorageProvider_1.IpfsStorageProvider(ipfsSettings);
                        return [2 /*return*/, new EthereumProofPointIssuer(rootAddress, ethereumAddressResolver, storageProvider, registry)];
                }
            });
        });
    };
    /**
     * Issue a new Proof Point
     * @param type A URI string identifying the type of Proof Point to issue. This may be any URL but there are some useful types defined defined in the Provenance ontology.
     * @param issuer A string identifying the Ethereum address from which to issue the Proof Point. This may be either an Ethereum address or a did:web URI. It must represent an account that you control and must be sufficiently funded to pay for the issuance transaction.
     * @param content A javascript object representing the type specific content of the payload. The shape of the data should conform to the specification of the @param type parameter.
     * @param [validFromDate] Optional date from which the issued Proof Point will be valid. If null then there is no earliest date at which the Proof Point is valid.
     * @param [validUntilDate] Optional date until which the issued Proof Point will be valid. If null then there is no latest date at which the Proof Point is valid.
     * @returns A @ProofPointIssueResult describing the result of the action.
     */
    EthereumProofPointIssuer.prototype.issue = function (type, issuer, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(type, issuer, content, function (c, id, issuer) { return c.issue(id, issuer); }, validFromDate, validUntilDate)];
            });
        });
    };
    /**
     * Commit a new Proof Point
     * @param type A URI string identifying the type of Proof Point to issue. This may be any URL but there are some useful types defined defined in the Provenance ontology.
     * @param issuer A string identifying the Ethereum address from which to commit the Proof Point. This may be either an Ethereum address or a did:web URI. It must represent an account that you control and must be sufficiently funded to pay for the issuance transaction.
     * @param content A javascript object representing the type specific content of the payload. The shape of the data should conform to the specification of the @param type parameter.
     * @param [validFromDate] Optional date from which the issued Proof Point will be valid. If null then there is no earliest date at which the Proof Point is valid.
     * @param [validUntilDate] Optional date until which the issued Proof Point will be valid. If null then there is no latest date at which the Proof Point is valid.
     * @returns A @ProofPointIssueResult describing the result of the action.
     */
    EthereumProofPointIssuer.prototype.commit = function (type, issuer, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._issue(type, issuer, content, function (c, id, issuer) { return c.commit(id, issuer); }, validFromDate, validUntilDate)];
            });
        });
    };
    /**
     * Revoke a Proof Point identified by it's ID. You must control the account that originally issued the Proof Point. The account must be sufficiently funded to execute the revoke transaction.
     * @param proofPointId The ID of the Proof Point to revoke. This is the value returned in the @param proofPointId field of the {@link ProofPointIssueResult} when the Proof Point was issued.
     */
    EthereumProofPointIssuer.prototype.revoke = function (proofPointId) {
        return __awaiter(this, void 0, void 0, function () {
            var storedData, proofPointObject, issuerAddress;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._storage.get(proofPointId.toString())];
                    case 1:
                        storedData = _a.sent();
                        proofPointObject = JSON.parse(storedData.data);
                        if (proofPointObject.proof.type !== ethereumProofPointRegistry_1.ETHEREUM_PROOF_TYPE) {
                            throw new Error("Unsupported proof type");
                        }
                        if (!this._registry.isSameRegistry(proofPointObject)) {
                            throw new Error("Registry mismatch");
                        }
                        return [4 /*yield*/, this._ethereumAddressResolver.resolve(proofPointObject.issuer)];
                    case 2:
                        issuerAddress = _a.sent();
                        if (issuerAddress === null) {
                            throw new Error("Cannot resolve issuer: " + proofPointObject.issuer);
                        }
                        return [4 /*yield*/, this._registry.revoke(proofPointId, issuerAddress)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    EthereumProofPointIssuer.prototype._buildProofPoint = function (type, issuer, content, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        var proofPoint = {
            "@context": [
                "https://www.w3.org/2018/credentials/v1",
                "https://provenance.org/ontology/ptf/v2",
            ],
            type: ["VerifiableCredential", type],
            issuer: issuer,
            credentialSubject: content,
            proof: {
                type: ethereumProofPointRegistry_1.ETHEREUM_PROOF_TYPE,
                registryRoot: this._rootAddress.toString(),
                proofPurpose: "assertionMethod",
                verificationMethod: issuer,
            },
            validFrom: undefined,
            validUntil: undefined,
        };
        if (validFromDate !== null) {
            proofPoint.validFrom = localISOdt.localISOdt(validFromDate);
        }
        if (validUntilDate !== null) {
            proofPoint.validUntil = localISOdt.localISOdt(validUntilDate);
        }
        return proofPoint;
    };
    EthereumProofPointIssuer.prototype._issue = function (type, issuer, content, issueFunction, validFromDate, validUntilDate) {
        if (validFromDate === void 0) { validFromDate = null; }
        if (validUntilDate === void 0) { validUntilDate = null; }
        return __awaiter(this, void 0, void 0, function () {
            var issuerAddress, proofPointObject, _a, id, canonicalisedObject, transactionHash;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this._ethereumAddressResolver.resolve(issuer)];
                    case 1:
                        issuerAddress = _b.sent();
                        if (issuerAddress === null) {
                            throw new Error("Cannot resolve issuer: " + issuer);
                        }
                        proofPointObject = this._buildProofPoint(type, issuer, content, validFromDate, validUntilDate);
                        return [4 /*yield*/, this._canonicalizeAndStoreObject(proofPointObject)];
                    case 2:
                        _a = _b.sent(), id = _a.id, canonicalisedObject = _a.canonicalisedObject;
                        return [4 /*yield*/, issueFunction(this._registry, id, issuerAddress)];
                    case 3:
                        transactionHash = _b.sent();
                        return [2 /*return*/, {
                                proofPointId: id,
                                transactionHash: transactionHash,
                                proofPointObject: canonicalisedObject,
                            }];
                }
            });
        });
    };
    EthereumProofPointIssuer.prototype._canonicalizeAndStoreObject = function (dataObject) {
        return __awaiter(this, void 0, void 0, function () {
            var cleanedDataObject, dataStr, storageResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cleanedDataObject = EthereumProofPointIssuer._removeEmptyFields(dataObject);
                        dataStr = canonicalize_1.default(cleanedDataObject);
                        return [4 /*yield*/, this._storage.add(dataStr)];
                    case 1:
                        storageResult = _a.sent();
                        return [2 /*return*/, {
                                id: proofPointId_1.ProofPointId.parse(storageResult.digest),
                                canonicalisedObject: JSON.parse(dataStr),
                            }];
                }
            });
        });
    };
    EthereumProofPointIssuer._removeEmptyFields = function (obj) {
        Object.keys(obj).forEach(function (key) {
            if (obj[key] && typeof obj[key] === "object")
                EthereumProofPointIssuer._removeEmptyFields(obj[key]);
            // eslint-disable-next-line no-param-reassign
            else if (obj[key] === undefined)
                delete obj[key];
        });
        return obj;
    };
    return EthereumProofPointIssuer;
}());
exports.EthereumProofPointIssuer = EthereumProofPointIssuer;
