$(function() {
    const Config = require('electron-config');
    const config = new Config();

    const sys = require('sys');
    const exec = require('child_process').exec;

    var download_progress = $('#download-progress');
    var format = "mp3";
    if(typeof config.get('format') !== 'undefined'){
        format = config.get('format');
    }
    var path = "";
    if(typeof config.get('path') !== 'undefined'){
        path = config.get('path');
    }
    var out = $('#output');
    var video = document.getElementById('video');
    const ipcRenderer = require('electron').ipcRenderer;
    const request = require('request');
    const helper = require('./../../helper/string');
    const helperx = require('./../../controller/webLoader/router');

    var shell = require('electron').shell;
       //open links externally by default
       $(document).on('click', 'a[href^="http"]', function(event) {
           event.preventDefault();
           shell.openExternal(this.href);
       });

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

    var cache = {};


    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">' + decodeURI(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 style="color: #FFF !important;text-shadow: #000000 0px 0px 9px;cursor: pointer;" class="btn btn-link play-file" data-file="' + 'file://' + path + '/' + encodeURI(helper.replace(cache[arg.id])) + '.' + format + '"><i class="fa  fa-2x fa-play-circle-o" aria-hidden="true"></i></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];
        config.set('path', path);
        console.log(path)
        ipcRenderer.send('setPath', {
            path: path
        });
    })
    $('#pot').click(function() {
        ipcRenderer.send('open-pot', {});
    });
    $('body').delegate('.play-file', 'click', function(e) {

        //exec(getCommandLine() + ' "' + decodeURI(e.currentTarget.dataset.file.split('file://')[1])+'"');
        if (pot === false) {
            video.setAttribute("src", e.currentTarget.dataset.file);
            video.play();
        } else {
            ipcRenderer.send('pot_run', {
                file: e.currentTarget.dataset.file
            });
        }
    })
    $('body').delegate('#navigota li','click',function(){
        console.log('TEST')
        $('#togmenu').click();
    })
    $('body').delegate('.format', 'click', function(e) {
        format = e.currentTarget.dataset.format;
        config.set('format', 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">
                  <img id="img-` + video_id + `"  class="d-flex align-self-start mr-3" src="..." alt="Generic placeholder image">
                  <div class="media-body" id="body-` + video_id + `">
                    <h5 class="mt-0">` + url + `</h5>
                    Author: ` + `
                    <div class="progress">
                      <div class="progress-bar"id="download-progress-` + video_id + `"  role="progressbar" style="width: 0%; height: 20px;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="media-out-` + video_id + `" style="    color: #FFF !important;
    text-shadow: #454545 1px 1px 1px;
    margin: auto;"></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">
                              <img id="img-` + video_id + `"  class="d-flex align-self-start mr-3" src="`+ YT.thumbnail_url +`" alt="Generic placeholder image">
                              <div class="media-body" id="body-` + video_id + `">
                                <h5 class="mt-0">` + YT.title + `</h5>
                                Author: ` + YT.author_name + `
                                <div class="progress">
                                  <div class="progress-bar"id="download-progress-` + video_id + `"  role="progressbar" style="width: 0%; height: 20px;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></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="d-flex alogn-self-start mr-3" style="
                                                                        background:url(`+YT.thumbnail_url+`);
                                                                        width: 189px;
                                                                        height: 104px;
                                                                        background-size: 189px;
                                                                        background-position: 0px -18px;
                                                                        ">
                                                                        <div class="media-out-` + video_id + `" style="    color: #FFF !important;
                                                        text-shadow: #454545 1px 1px 1px;
                                                        margin: auto;"></div>
                                                                        </div>
                          <div class="media-body" id="body-` + video_id + `">
                            <h5 class="mt-0">` + YT.title + `</h5>
                            Author: ` + YT.author_name + `
                            <div class="progress">
                              <div class="progress-bar"id="download-progress-` + video_id + `"  role="progressbar" style="width: 0%; height: 20px;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
                            </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)

        }

    })

    $('#close').click(function() {
        console.log('TEST')
        ipcRenderer.send('winHide', {

        });
    })

    function getCommandLine() {
       switch (process.platform) {
          case 'darwin' : return 'open';
          case 'win32' : return 'start';
          case 'win64' : return 'start';
          default : return 'xdg-open';
       }
    }
})
