<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dice-Tower - Overlay</title>
    <link rel="icon" type="image/png" href="/favicon.png">
    <link rel="stylesheet" href="/overlay/style.css">
    <script src="/vendor/comfy.js/comfy.min.js"></script>
</head>
<body>
<div id="dice-box"></div>
<div popover id="results" class="tooltip">
</div>
<script type="module">
    import DiceBox from "/vendor/dice-box/dice-box-threejs.es.js";
    const diceBox = new DiceBox("#dice-box", {
        assetPath: "/vendor/dice-box/",
        light_intensity: 2,
        gravity_multiplier: 600,
        baseScale: {scale} * 10,
        strength: Math.floor(Math.random() * 4),
        theme_customColorset: {
            texture: '{theme}',
            background: '{faceColor}',
            foreground: '{numberColor}'
        }
    });
    diceBox.initialize();
    ComfyJS.Init('{channel}');

    //maxDice

    ComfyJS.onCommand = async (user, command, message, flags) => {
        if ((flags.broadcaster || {allAllowed} || ({modsAllowed} && flags.mod) || ({vipAllowed} && flags.vip) || ({subsAllowed} && flags.subscriber)) && '{cmd}' === command && !shouldWait() && message.match(/^\d+d(4|6|8|10|12|20|100)$/) && (+message.split('d')[0] <= {maxDice})
        ) {
            toggleWait(true);

            diceBox.onRollComplete = (rollResult) => {
                rollResult.sets.forEach(result => {
                    let values = []
                    result.rolls.forEach(roll => {
                        values.push(roll.value);
                    })
                    document.getElementById('results').innerHTML = '<strong>' + user + '</strong> rolls <strong>' + message + '</strong>:<br/> [' + values.map(value => value === 1 ? '<strong style="text-shadow: 2px 2px 10px red">' + value + '</strong>' : value === result.sides ? '<strong style="text-shadow: 2px 2px 10px green">' + value + '</strong>' : value).join(' + ') + '] = <strong>' + result.total + '</strong> '
                })
                if({showResults}) {
                    document.getElementById('results').showPopover()
                }
                setTimeout(() => {
                    diceBox.clearDice();
                    document.getElementById('results').hidePopover()
                }, {clearAfter} * 1000)
            }

            diceBox.roll(message);
            setTimeout(() => {
                toggleWait(false);
            }, {clearAfter} * 1000 + {timeout} * 1000)
        } else {
            console.log('Not a valid command or not ready yet');
        }
    };

    let wait;

    function shouldWait() {
        return wait;
    }

    function toggleWait(value) {
        wait = value;
    }
</script>
</body>
</html>
