"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScaffoldVisitor = void 0;
const ast_1 = require("@wapc/widl/ast");
const utils_1 = require("../utils");
const helpers_1 = require("./helpers");
class ScaffoldVisitor extends ast_1.BaseVisitor {
    constructor(writer) {
        super(writer);
    }
    visitDocumentBefore(context) {
        const useName = context.config["use"] || "generated";
        super.visitDocumentBefore(context);
        this.write(`mod ${useName};
extern crate wapc_guest as guest;
use guest::prelude::*;
pub use ${useName}::*;\n\n`);
    }
    visitAllOperationsBefore(context) {
        const registration = new HandlerRegistrationVisitor(this.writer);
        context.document.accept(context, registration);
    }
    visitOperation(context) {
        if (!utils_1.shouldIncludeHandler(context)) {
            return;
        }
        const operation = context.operation;
        this.write(`\n`);
        this.write(`fn ${helpers_1.functionName(operation.name.value)}(${helpers_1.mapArgs(operation.arguments, true)}) -> HandlerResult<`);
        if (!helpers_1.isVoid(operation.type)) {
            this.write(helpers_1.expandType(operation.type, undefined, true, helpers_1.isReference(operation.annotations)));
        }
        else {
            this.write(`()`);
        }
        this.write(`> {\n`);
        if (!helpers_1.isVoid(operation.type)) {
            const dv = helpers_1.defaultValueForType(operation.type, undefined);
            this.write(`    Ok(${dv})`);
        }
        else {
            this.write(`    Ok(())`);
        }
        this.write(` // TODO: Provide implementation.\n`);
        this.write(`}\n`);
    }
}
exports.ScaffoldVisitor = ScaffoldVisitor;
class HandlerRegistrationVisitor extends ast_1.BaseVisitor {
    constructor(writer) {
        super(writer);
    }
    visitAllOperationsBefore(context) {
        this.write(`#[no_mangle]
pub fn wapc_init() {\n`);
    }
    visitOperation(context) {
        if (!utils_1.shouldIncludeHandler(context)) {
            return;
        }
        const operation = context.operation;
        this.write(`    Handlers::register_${helpers_1.functionName(operation.name.value)}(${helpers_1.functionName(operation.name.value)});\n`);
    }
    visitAllOperationsAfter(context) {
        this.write(`}\n`);
    }
}
//# sourceMappingURL=scaffold_visitor.js.map