/* IMPORT */
import decode from 'decode-base64';
import once from 'function-once';
import wrapper from '../graphviz/wrapper.js';
import { DEFAULT_ENGINE, DEFAULT_FORMAT } from './constants.js';
/* MAIN */
const generate = (GRAPHVIZ_BASE64) => {
    const Graphviz = {
        /* LIFECYCLE API */
        loadWASM: once(async () => {
            const GRAPHVIZ_BUFFER = decode(GRAPHVIZ_BASE64);
            const instance = await wrapper({ wasmBinary: GRAPHVIZ_BUFFER });
            Graphviz.layout = (source, format = DEFAULT_FORMAT, engine = DEFAULT_ENGINE) => {
                const graphviz = new instance.Graphviz();
                const result = graphviz.layout(source, format, engine);
                instance.destroy(graphviz);
                if (!result)
                    throw new Error(instance.Graphviz.prototype.lastError());
                return result;
            };
        }),
        /* API */
        layout: (source, format = DEFAULT_FORMAT, engine = DEFAULT_ENGINE) => {
            throw new Error('[graphviz] You need to call and await "graphviz.loadWASM" first');
        }
    };
    return Graphviz;
};
/* EXPORT */
export default generate;
