<script lang="ts">
    /// <reference path="../editor/defaultEnv.d.ts" />
    import { onMount } from "svelte";
    import { code } from "../editor/code";
    import { dmxData } from "../dmx/store";
    import { lib } from "./lib";
    import TS from "typescript";
    import tsOptions from "./tsOptions";

    $: transpiled = TS.transpile($code, tsOptions);

    let startTime: number;
    let payload = new Uint8Array(512);
    let ctx: Context = {
        set(address: number, value: number) {
            let rounded = Math.round(value);
            payload[address - 1] = Math.max(0, Math.min(255, rounded));
        },
    };

    let result: string;

    function dmxFrame() {
        payload = new Uint8Array(512);
        const t = (performance.now() - startTime) / 1000;
        try {
            let ret = Function("ctx", "t", "lib", transpiled).call({}, ctx, t, lib);
            result = JSON.stringify(ret);
        } catch (err) {
            result = JSON.stringify(err);
        }
        $dmxData = payload;
    }

    const FPS = 50;
    const FRAME_TIME = 1000 / FPS; // milliseconds

    onMount(() => {
        startTime = performance.now();

        let int = setInterval(dmxFrame, FRAME_TIME);

        return () => {
            clearInterval(int);
        };
    });
</script>

<!-- <pre>{result}</pre> -->
