<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>


<div class="container center_div">
    <form class="form-inline" id="download-form">
        <div class="form-group mx-sm-3 mb-2">
            <label for="download-input" class="sr-only">Youtube Link</label>
            <input type="url" class="form-control" name="download-url" placeholder="Youtube Link">
        </div>
        <button type="submit" id="download-button" class="btn btn-primary mb-2" onclick="this.disabled = true;">Download</button>
    </form>
</div>


<div class="container">
    <div class="progress">
        <div class="progress-bar progress-bar-striped progress-bar-animated progress-bar-success active"
            role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
            0%
        </div>
    </div>
</div>

<script>
    $("#download-form").submit(function (e) {
        e.preventDefault()

        // Reset the progress bar counter for the new download
        $(".progress-bar")
            .css("width", "0%")
            .attr("aria-valuenow", 0)
            .text("0%")
            .addClass("progress-bar-animated active")

        // Create the websocket connection that'll indicate the URL we 
        // intend to download and that'll report download progress
        var ws = new WebSocket("{{ url_for('websocket_endpoint') }}");
        ws.onopen = function (event) {
            download_url = $('input[name=download-url]').val()
            ws.send(download_url)
        }
        ws.onmessage = function (event) {
            event.preventDefault()
            $(".progress-bar")
                .css("width", event.data + "%")
                .attr("aria-valuenow", event.data)
                .text(event.data + "%")
        };

        // Download the file and then get it
        var formData = new FormData();
        formData.append("url", $('input[name=download-url]').val())
        fetch("{{ url_for('download') }}",
            {
                method: 'post',
                body: JSON.stringify({ "url": $('input[name=download-url]').val() }),
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                }
            })
            .then(function (response) {
                if (!response.ok) {
                    document.getElementById("download-button").disabled = false;
                    throw Error(response.statusText);
                }
                return response.json();
            }).then(function (resp) {
                // Stop the progress bar's animation
                $(".progress-bar")
                    .removeClass("progress-bar-animated active")
                // Re-enable the download button
                document.getElementById("download-button").disabled = false;

                var element = document.createElement('a');
                element.setAttribute('download', resp.filename);
                element.setAttribute('href', `{{ url_for('downloads', path='${resp.filename}') }}`);
                document.body.appendChild(element);
                element.click();
                document.body.removeChild(element);
            })
    })
</script>