<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dice-Tower</title>
    <script src="/vendor/color-picker.js"></script>
    <style>
        .collapsible {
            background-color: #b218cd;
            color: black;
            cursor: pointer;
            margin-top: 10px;
            padding: 18px;
            width: 100%;
            border: none;
            text-align: left;
            outline: none;
            font-size: 15px;
        }

        .content {
            padding: 0 18px;
            display: none;
            overflow: hidden;
            background-color: black;
        }
    </style>
</head>
<body>
<h1>Dice-Tower</h1>
<p>Welcome to Dice-Tower</p>
<label for="name" id="nameLabel">Name </label><input type="text" id="name" style="width: 500px" required/><br/>
<label for="room" id="roomLabel">Room </label><input type="text" id="room" style="width: 500px" required/><br/>
<div id="dice-tower" hidden>
    <label for="overlayId">Overlay </label><input type="text" readonly id="overlayId" style="width: 500px"/>
    <br/>
    <label for="theme">Theme </label>
    <select name="theme" id="theme">
        <option value="default">Default</option>
        <option value="blueGreenMetal">Blue-Green Metal</option>
        <option value="diceOfRolling">Dice of Rolling</option>
        <option value="gemstone">Gemstone</option>
        <option value="gemstoneMarble">Marble Gemstone</option>
        <option value="rock">Rock</option>
        <option value="rust">Rust</option>
        <option value="smooth">Smooth</option>
        <option value="wooden">Wooden</option>
    </select>
    <br/>
    <button type="button" class="collapsible">Theme Color</button>
    <div class="content">
        <color-picker value="#b218cd" id="themeColor"></color-picker>
    </div><br/>
    <p>Example Commands: "1d6", "2d8 1d100", "5d6+10"</p>
    <label for="command">Command </label><input type="text" id="command"/><br/><br/>
</div>
<button hidden id="roll" onclick="roll()">Roll
</button>
<button id="start" onclick="start()">Start
</button>
<br/>
<div id="results">

</div>
<script>
    function start() {
        if(document.getElementById('name').value.length > 0 && document.getElementById('room').value.length > 0) {
            document.getElementById('overlayId').value = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/overlay/' + document.getElementById('room').value + ':' + localStorage.getItem('userId');
            document.getElementById('roll').hidden = false;
            document.getElementById('start').hidden = true;
            document.getElementById('dice-tower').hidden = false;
            document.getElementById('name').hidden = true;
            document.getElementById('room').hidden = true;
            document.getElementById('nameLabel').innerHTML = 'Name: <strong>' + document.getElementById('name').value + '</strong>';
            document.getElementById('roomLabel').innerHTML = 'Room: <strong>' + document.getElementById('room').value + '</strong>';

            const evtSource = new EventSource(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/dice/' + document.getElementById('room').value + '/results');
            evtSource.addEventListener('message', function (event) {
                console.log(event.data)
                let data = JSON.parse(event.data);
                let name = document.getElementById(data.name) ?? document.createElement('div');
                name.id = data.name;
                name.replaceChildren(...[]);
                let node = document.createElement('p');
                let resultText = ''
                if (!data.results) {
                    resultText = ' rolling...'
                } else {
                    data.results.forEach(result => {
                        let values = []
                        result.rolls.forEach(roll => {
                            values.push(roll.value);
                        })
                        resultText += ' (' + values.join(' + ') + (result.modifier > 0 ? ' <a style="text-decoration: underline">+' + result.modifier + '</a>': result.modifier < 0 ? ' <a style="text-decoration: underline">' + result.modifier + '</a>': '') + ' = <strong style="font-size: x-large">' + result.value + '</strong>) '
                    })
                }
                node.innerHTML = '<strong>' + data.name + ':</strong> &#127922;	' + resultText
                name.appendChild(node)
                document.getElementById('results').appendChild(name);
            })
        }
    }

    function roll() {
        if(document.getElementById('name').value.length > 0 && document.getElementById('room').value.length > 0) {
            let httpRequest = new XMLHttpRequest();
            httpRequest.open('POST',window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/dice/' + document.getElementById('room').value + ':' + localStorage.getItem(`userId`))
            httpRequest.setRequestHeader('Content-Type', 'application/json')
            httpRequest.send(JSON.stringify({
                name: document.getElementById('name').value,
                command: document.getElementById('command').value,
                themeColor: document.getElementById('themeColor').value,
                theme: document.getElementById('theme').value
            } ))
        }
    }

    let coll = document.getElementsByClassName("collapsible");

    for (let i = 0; i < coll.length; i++) {
        coll[i].addEventListener("click", function () {
            coll[i].style['background-color'] = document.getElementById('themeColor').value;
            const content = this.nextElementSibling;
            if (content.style.display === "block") {
                content.style.display = "none";
                this.classList.remove("active");
            } else {
                this.classList.add("active");
                for (let c of coll) {
                    const cont = c.nextElementSibling;
                    if (cont !== content) {
                        c.classList.remove("active");
                        cont.style.display = "none";
                    }
                }
                content.style.display = "block";
            }
        });
    }
    if (!localStorage.getItem("userId")) {
        localStorage.setItem("userId", self.crypto.randomUUID());
    }
</script>
</body>
</html>
