import { Annotated, Bytes, Set, Dictionary, Fold, fold, Record, Tuple, Value, stringify, Embedded } from "@preserves/core";
import { brackets, Item, parens, seq } from "./block";
import * as M from '../meta';

export function sourceCodeFor(v: Value<M.InputEmbedded>): Item {
    return fold(v, {
        boolean(b: boolean): Item { return b.toString(); },
        single(f: number): Item { return f.toString(); },
        double(f: number): Item { return f.toString(); },
        integer(i: number): Item { return i.toString(); },
        string(s: string): Item { return JSON.stringify(s); },
        bytes(b: Bytes): Item {
            return seq(`Uint8Array.from(`, brackets(... Array.from(b).map(b => b.toString())), `)`);
        },
        symbol(s: symbol): Item { return `_.Symbol.for(${JSON.stringify(s.description!)})`; },

        record(r: Record<Value<M.InputEmbedded>, Tuple<Value<M.InputEmbedded>>, M.InputEmbedded>, k: Fold<M.InputEmbedded, Item>): Item {
            return seq(`_.Record<_.Value<_embedded>, _.Tuple<_.Value<_embedded>>, _embedded>`, parens(k(r.label), brackets(... r.map(k))));
        },
        array(a: Array<Value<M.InputEmbedded>>, k: Fold<M.InputEmbedded, Item>): Item {
            return brackets(... a.map(k));
        },
        set(s: Set<M.InputEmbedded>, k: Fold<M.InputEmbedded, Item>): Item {
            return seq('new _.Set<_.Value<_embedded>>', parens(brackets(... Array.from(s).map(k))));
        },
        dictionary(d: Dictionary<M.InputEmbedded>, k: Fold<M.InputEmbedded, Item>): Item {
            return seq('new _.Dictionary<_embedded>', parens(brackets(... Array.from(d).map(([kk,vv]) =>
                brackets(k(kk), k(vv))))));
        },

        annotated(a: Annotated<M.InputEmbedded>, k: Fold<M.InputEmbedded, Item>): Item {
            return seq('_.annotate<_embedded>', parens(k(a.item), ... a.annotations.map(k)));
        },

        embedded(t: Embedded<M.InputEmbedded>, _k: Fold<M.InputEmbedded, Item>): Item {
            throw new Error(`Cannot emit source code for construction of embedded ${stringify(t)}`);
        },
    });
}
