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

    let startTime: number;
    let payload = new Uint8Array(512);
    let ctx: Context = {
        set(address: number, value: number) {
            payload[address - 1] = value;
        }
    }

    let result: string;

    function dmxFrame() {
        payload = new Uint8Array(512);
        const t = (performance.now() - startTime) / 1000;
        try {
            let ret = Function("ctx", "t", $code).call({}, ctx, t);
            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> -->