<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>AudioWire</title>
    <link rel="stylesheet" href='{{static_url("bootstrap-4.0.0-dist/css/bootstrap.min.css")}}'>
    <style>
        .color-red {
            color: red;
        }

        .ul-clean {
            padding-left: 0px;
        }

        .ul-clean>li {
            list-style-type: none;
        }

        .number {
            font-family: 'Courier New', Courier, monospace
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-light bg-light">
        <a class="navbar-brand" href="javascript:void(0);">
            <img src="/static/favicon.ico" width="30" height="30" class="d-inline-block align-top" alt="">
            AudioWire <small>{{version}}</small>
        </a>
    </nav>

    <div id="app" class="container" style="padding-top: 15px">
        <div v-if="!playing">
            <button type="button" class="btn btn-info form-control" @click="play">播放</button>
        </div>
        <div v-else>
            <button type="button" class="btn btn-dark form-control" @click="stop">停止</button>
        </div>
        <hr>
        主机: <span class="number" v-text="location.host"></span>
        <div>
            <ul class="ul-clean">
                <li>设备: <span class="number" style="font-weight: 100" v-text="opts.name"></span></li>
                <li>频率: <span class="number" v-text="opts.sampleRate"></span></li>
                <li>通道: <span class="number" v-text="opts.channels"></span></li>
                <li>延迟: <span class="number" v-text="delay"></span> ms &lt; <span class="number"
                        v-text="maxDelay"></span>
                    <a v-show="playing" href="javascript:;" @click="ws.refresh()">重连</a></li>
            </ul>
        </div>
        <div v-if="playing" class="text-center">
            <img class="rounded" src="{{static_url('favicon.ico')}}">
        </div>
        <div v-text="message" class="color-red"></div>
    </div>
    <script src='{{static_url("jquery.min.js")}}'></script>
    <script src='{{static_url("pcmplayer2.js")}}'></script>
    <script src='{{static_url("vue.js")}}'></script>
    <script src='{{static_url("reconnecting-websocket.js")}}'></script>
    <script src='{{static_url("bootstrap-4.0.0-dist/js/bootstrap.min.js")}}'></script>
    <script src='{{static_url("NoSleep.js")}}'></script>
    <script>
        // Disable zooming on mobile safari
        document.addEventListener('gesturestart', function (e) {
            e.preventDefault();
        });
    </script>
    <script>
        new Vue({
            el: "#app",
            data: {
                opts: {},
                player: null,
                playing: false,
                message: "",
                delay: 0, // ms
                maxDelay: 400, // milliseconds
                interval: null,
                ws: null,
                noSleep: new NoSleep(),
            },
            mounted() {
                $.getJSON("/audio").then(ret => {
                    this.opts = Object.assign({}, ret, { maxDelay: this.maxDelay / 1000 })
                })
            },
            methods: {
                play() {
                    this.message = ""
                    this.interval = setInterval(() => {
                        this.delay = Math.floor(this.player.delay * 1000)
                    }, 500)
                    this.playWebSocket(this.opts)
                    this.noSleep.enable()
                },
                stop() {
                    if (this.playing) {
                        this.ws.close()
                        clearInterval(this.interval)
                        this.noSleep.disable()
                    }
                },
                playWebSocket(opts) {
                    const socketURL = `ws://${location.host}/audio/websocket`;
                    this.player = new PCMPlayer(opts)

                    let ws = new ReconnectingWebSocket(socketURL, null, {
                        binaryType: "arraybuffer",
                        maxReconnectAttempts: 5,
                    });
                    this.ws = ws;

                    ws.onopen = (event) => {
                        this.playing = true
                        console.log("websocket connected")
                    }

                    ws.addEventListener('message', (event) => {
                        const data = new Uint8Array(event.data);
                        this.player.feed(data);
                    });

                    ws.addEventListener("close", (event) => {
                        console.log("websocket closed")
                    })

                    ws.addEventListener("destroy", (event) => {
                        this.playing = false
                        this.player.destroy()
                        console.log("ReconnectingWebSocket closed")
                    })
                },
            },
            computed: {
                location() {
                    return window.location
                }
            }
        })
    </script>
</body>

</html>