<%include partials/header.ejs %>

<div class="container">
    <div class="row">
        <div class="col-md-8">
            <!-- duckdns-> oVrbkDUrX727MjQd4zq7nRw1XEHkkpGErE -->
            <label for="flo-addr">Enter the flo address (oHyzdt8xW1A81qcZ5VcM25RbC6RVbynAg4)</label>
            <input type="text" id="flo-addr" class="form-control" />

            <p><button id="flo-addr-btn" class="btn btn-primary">Get Torrents List</button></p>

            <ul id="flo-res" class="list-group"></ul>  

            <label for="mag_text">Provide a magnetic URL below:</label>
            <p><button id="dwn-seed" class="btn btn-primary">View Torrent</button></p>
        </div>

        <div class="col-md-4">
            
            <div class="mt-2 mb-2">
                <p id="tmsg" class="text-info"></p>
                <p id="dwld"></p>
                <div id="mag-res"></div>
            </div>
        
        </div>
    </div>

</div>

<%include partials/footer.ejs %>

<script>
    $(document).on('click', '#flo-addr-btn', function() {
        var floaddr = $("#flo-addr").val();
        if (floaddr.length<1) {
            alert("Please specify a FLO address.");
            return;
        }

        var job = 'flo-comment';
        
        $.ajax({
            url: '/fetch-from-blockchain',
            type: 'post',
            data: {job:job, floaddr:floaddr},
            success: function(response) {
                var t = '';
                if (response.msg.length>0) {
                    t += `<li class="list-group-item list-group-item-light"><h5 class="text-info">${response.msg}</h5></li>`;
                }

                if (response.error==false && typeof response.data != undefined) {
                    for (let fd = 0; fd < response.data.length; fd++) {
                        if (response.data[fd][0] != null && response.data[fd][1] != null) {
                            const fdata = response.data[fd];
  
                            t += `<li class="list-group-item">`;
                            t += `<div class="input-group">`;
                            t += `<div class="input-group-prepend">`;
                            t += `<div class="input-group-text">`;
                            t += `<input type="radio" name="magrads" value="${fdata[1]}" aria-label="Radio button for magnetic url">`;
                            t += `</div>`;
                            t += `</div>`;
                            t += `<input type="text" value="${fdata[0]}" class="form-control" aria-label="Text input with radio button">`;
                            t += `</div>`;
                            t += `</li>`;   
                        }
                    }
                }
                $("#flo-res").html(t);
            },
            error: function(e) {
                console.error(e);
            }
        });
    });

    $(document).on('click', '#dwn-seed', function() {
        
        var client = new WebTorrent()

        var torrentId = $('input[name=magrads]:checked').val();

        if (torrentId.trim() == '') {
            alert("Please specify a magnetic url.");
            return;
        }
        torrentId = torrentId.replace("text:", "");

        document.getElementById("tmsg").innerText = "The download link will appear here in few momments."

        client.add(torrentId, function (torrent) {
        // Torrents can contain many files. Let's use the .mp4 file
        var file = torrent.files.find(function (file) {
            console.log(file);
            if (file.name.endsWith('.mp4')) {
                return file.name.endsWith('.mp4')    
            } else if (file.name.endsWith('.webm')) {
                return file.name.endsWith('.webm')    
            } else if (file.name.endsWith('.avi')) {
                return file.name.endsWith('.avi')    
            } else if (file.name.endsWith('.pdf')) {
                return file.name.endsWith('.pdf')    
            } else if (file.name.endsWith('.mp3')) {
                return file.name.endsWith('.mp3')    
            } else if (file.name.endsWith('.jpg')) {
                return file.name.endsWith('.jpg')    
            } else if (file.name.endsWith('.png')) {
                return file.name.endsWith('.png')    
            } else if (file.name.endsWith('.gif')) {
                return file.name.endsWith('.gif')    
            } else if (file.name.endsWith('.jpeg')) {
                return file.name.endsWith('.jpeg')    
            } 
        })

        console.log('Client is downloading:', torrent.infoHash)
        
        // Display the file by adding it to the DOM. Supports video, audio, image, etc. files
        file.appendTo('#mag-res')

        file.getBlobURL(function (err, url) {
            if (err) throw err
            var a = document.createElement('a')
            a.download = file.name
            a.href = url
            a.textContent = 'Download ' + file.name + ' (' +file.length/1000+ ' Kb)'
            document.getElementById("dwld").appendChild(a)
        })

        })

    });

</script>