$(function() {
    var download_progress = $('#download-progress');
    var format = null;
    var out = $('#output');
    var video = document.getElementById('video');
    const ipcRenderer = require('electron').ipcRenderer;
    const request = require('request');
    const helper = require('./../../helper/string');

    const {
        dialog
    } = require('electron').remote;

    var cache = {};
    var path = "";

    var pot = false;

    ipcRenderer.send('watchr_event', {});
    ipcRenderer.on('play-in-Window',function(event,arg){
        pot = arg.do;
    })
    ipcRenderer.on('watchr_file', function(event, arg) {
        arg.file = encodeURI(arg.file)
        if (arg.type === "add") {
            $('#watchr_files').append('<div class="row-flex file" data-file="' + arg.file + '"><div class="flex-btn"><button class="play-file btn btn-success" data-file="' + 'file://' + arg.file + '"><i class="fa fa-play-circle-o" aria-hidden="true"></i></button></div><div class="cont">' + arg.file + '</div></tr>')
        } else if (arg.type === "remove") {
            $('.file[data-file="' + arg.file + '"]').remove();
        }
        $('#download-progress-' + arg.id).html(arg.percent);
    })
    ipcRenderer.on('download-progress', function(event, arg) {
        console.log(arg); // prints "pong"
        $('#download-progress-' + arg.id).css("width", arg.percent);
        $('#download-progress-' + arg.id).html(arg.percent);
    });
    ipcRenderer.on('process-fin', function(event, arg) {
        console.log(arg); // prints "pong"
        $('#download-progress-' + arg.id).css("width", arg.percent);
        $('#download-progress-' + arg.id).html("CONVERTED");
    });
    ipcRenderer.on('file', function(event, arg) {
        console.log('DOWNLOADED')
        console.log(arg); // prints "pong"

        $('.media-out-' + arg.id).html('<button class="play-file" data-file="' + 'file://' + path + '/' + encodeURI(cache[arg.id]) + '.' + format + '">Play</button>');
        //var video = document.getElementById('video');
        //$('#body-' + arg.id).append('<audio src="file://' + path + '/' + cache[arg.id] + '.'+format+'" controls="true"/>');
    });
    document.getElementById('party').addEventListener('click', _ => {
        path = dialog.showOpenDialog({
            properties: ['openDirectory']
        })[0];
        console.log(path)
        ipcRenderer.send('setPath', {
            path: path
        });
    })
    $('#pot').click(function(){
        ipcRenderer.send('open-pot', {
        });
    });
    $('body').delegate('.play-file', 'click', function(e) {
        if(pot === false){
            video.setAttribute("src", e.currentTarget.dataset.file);
            video.play();
        }else{
            ipcRenderer.send('pot_run', {file:e.currentTarget.dataset.file});
        }
    })
    $('body').delegate('.format', 'click', function(e) {
        format = e.currentTarget.dataset.format;
        ipcRenderer.send('set-format', {
            format: e.currentTarget.dataset.format
        });
        console.log(e.currentTarget.dataset.format);
    })
    $('#start-download').click(function() {
        var url = $('#url').val();

        if (url.match('crunchyroll')) {
            var video_id = Math.floor(Date.now() / 1000);
            $('<div class="media" ><div class="media-left"><a href="#"><img id="img-' + video_id + '" width="128" class="media-object" src="' + '" alt="..."></a></div><div class="media-body" id="body-' + video_id + '"><h4 class="media-heading">' + url + '</h4> Author: ' + '<div class="progress"><div class="progress-bar" id="download-progress-' + video_id + '" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">0%</div></div><div class="media-out-' + video_id + '"></div></div></div>').prependTo('#output');
            ipcRenderer.send('start-download', {
                url: $('#url').val(),
                id: video_id
            });
        } else {

            var video_id = $('#url').val().split('v=')[1];
            var ampersandPosition = video_id.indexOf('&');
            if (ampersandPosition != -1) {
                video_id = video_id.substring(0, ampersandPosition);
            }
            var playlist_id = $('#url').val().split('list=')[1];
            if (typeof playlist_id !== 'undefined') {
                var playlist_idPOS = playlist_id.indexOf('&');
                if (playlist_idPOS != -1) {
                    playlist_id = playlist_id.substring(0, playlist_idPOS);
                }

                request
                    .get('https://www.youtube.com/oembed?url=https://www.youtube.com/playlist?list=' + playlist_id + '&format=json', function(err, httpResponse, body) {
                        var YT = JSON.parse(body);
                        $('<div class="media" ><div class="media-left"><a href="#"><img id="img-' + video_id + '" width="128" class="media-object" src="' + YT.thumbnail_url + '" alt="..."></a></div><div class="media-body" id="body-' + video_id + '"><h4 class="media-heading">' + YT.title + '</h4> Playlistauthor: ' + YT.author_name + '<div class="progress"><div class="progress-bar" id="download-progress-' + video_id + '" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">0%</div></div><div class="media-out-' + video_id + '"></div></div></div>').prependTo('#output');
                        cache[video_id] = YT.title;
                        ipcRenderer.send('start-download-pl', {
                            url: $('#url').val(),
                            id: video_id,
                            folder: YT.author_name + '-' + YT.title.replace(/\|/g, "_")
                        });
                    })
            } else {
                request
                    .get('https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' + video_id + '&format=json', function(err, httpResponse, body) {
                        var YT = JSON.parse(body);
                        $('<div class="media" ><div class="media-left"><a href="#"><img id="img-' + video_id + '" width="128" class="media-object" src="' + YT.thumbnail_url + '" alt="..."></a></div><div class="media-body" id="body-' + video_id + '"><h4 class="media-heading">' + YT.title + '</h4> Author: ' + YT.author_name + '<div class="progress"><div class="progress-bar" id="download-progress-' + video_id + '" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 00%;">0%</div></div><div class="media-out-' + video_id + '"></div></div></div>').prependTo('#output');
                        cache[video_id] = YT.title;
                        ipcRenderer.send('start-download', {
                            url: $('#url').val(),
                            id: video_id
                        });
                    })
            }
            console.log(playlist_id + ' id:' + video_id)

        }

    })
})
