"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEvent = void 0;
const libp2p_crypto_1 = require("libp2p-crypto");
const loglevel_1 = __importDefault(require("loglevel"));
const threads_core_1 = require("@textile/threads-core");
const coding_1 = require("./coding");
const logger = loglevel_1.default.getLogger('encoding:event');
/**
 * CreateEvent creates a new Event object using the input raw Event body.
 * @param body Input block. Should be an IPLD Block wrapping the raw Event body.
 * @param readKey The input read key for encrypting the Event wrapper.
 * @param key The input symmetric key for raw data encryption.
 * @param opts Additional encoding/encryption options.
 */
function createEvent(body, readKey, key, opts = coding_1.defaultOptions) {
    return __awaiter(this, void 0, void 0, function* () {
        logger.debug('creating event');
        const keyiv = key || libp2p_crypto_1.randomBytes(32);
        const codedBody = coding_1.encodeBlock(body, keyiv);
        const header = { key: keyiv };
        const eventHeader = threads_core_1.Block.encoder(header, opts.codec, opts.algo);
        const codedHeader = coding_1.encodeBlock(eventHeader, readKey, opts);
        // Encode to create the caches
        codedBody.encode();
        codedHeader.encode();
        const obj = {
            body: yield codedBody.cid(),
            header: yield codedHeader.cid(),
        };
        const codedEvent = threads_core_1.Block.encoder(obj, opts.codec, opts.algo);
        codedEvent.encode();
        // @todo: We don't support a dag here yet, but this is where we'd add this data to IPFS!
        const event = {
            value: codedEvent,
            header: codedHeader,
            body: codedBody,
        };
        return event;
    });
}
exports.createEvent = createEvent;
//# sourceMappingURL=event.js.map