
const urlField = document.getElementById('download_text_box');

const downloadBtn = document.getElementById('download_button');

const dlType = document.getElementById('selector');

const res = document.getElementById('res_selector');

const video_url = document.getElementById('video_link');
const myTitle = document.getElementById('video_title');

const channel_url = document.getElementById('channel_link');
const channel_title = document.getElementById('channel_name');

const my_date = document.getElementById('date');

const size_len = document.getElementById('size_len');

const myViews = document.getElementById('views');
const myKeywords = document.getElementById('keywords');
const myDescription = document.getElementById('description');
const myProgress = document.getElementById('progress_bar');
const myProgressVal = document.getElementById('progress_value');
function sec2time(given_seconds){
   var dateObj = new Date(parseInt(given_seconds) * 1000);
   hours = dateObj.getUTCHours();
   minutes = dateObj.getUTCMinutes();
   seconds = dateObj.getSeconds();

   return hours.toString().padStart(2, '0')
       + ':' + minutes.toString().padStart(2, '0')
       + ':' + seconds.toString().padStart(2, '0');

}
function progress2page()
{
   var xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myData = JSON.parse(this.responseText);
    var progressStr=myData.Progress.toString() + '%';
    var progressData = myData.Progress;
    //var fileLength = formatBytes(myData.Length);
    var title = myData.Saved.Title;
    var uploadDate = new Date(myData.Saved.UploadDate);
    var id = myData.Saved.Id;
    var atitle = myData.Saved.AuthorTitle;
    var acid = myData.Saved.AuthorChannelId;
    var desc = myData.Saved.Description;
    //var dur = sec2time(myData.Saved.Duration);
    var views = myData.Saved.Views;
    var likes = myData.Saved.Likes;
    var dislikes = myData.Saved.Dislikes;
    myProgress.setAttribute("value", progressData.toString());
    myProgressVal.textContent = progressStr;
    
    myDescription.textContent = desc;
    myTitle.textContent = title;
    channel_title.textContent = atitle;
    myViews.textContent = views.toString() + " view(s) - " + likes.toString() + " like(s) - " + dislikes.toString() + " dislikes";
   
    channel_url.href = "https://www.youtube.com/channel/" + acid;
    video_url.href = "https://www.youtube.com/watch?v=" + id;
    
    my_date.textContent = (uploadDate.getMonth() + 1).toString() + '/' + uploadDate.getDate().toString() + '/' + uploadDate.getFullYear().toString();
      let kw = "";  
    myData.Saved.Keywords.forEach((item, index) => {
         if(index == 0)
         {
            kw = item;
         }else{
            kw += ", " + item;
         }

      });
      
      keywords.textContent = kw;
   }
   //if(!(fileLength === undefined || dur ))
   {
      //size_len.textContent = fileLength + " - " + dur;
   }
};
xmlhttp.open("GET", "api/Progress", true);
xmlhttp.send();
}

function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}
downloadBtn.addEventListener('click',()=>{
   
    let url =urlField.value;
    
    let opt = parseInt(dlType.value);
    
   if(opt == 0)
   {
         
         var req = new XMLHttpRequest();
         req.open("GET","api/AddVideoRes/" + res.value + '/' + url);
         req.send(null);
   }
   if(opt == 1)
   {
      var req = new XMLHttpRequest();
      req.open("GET","api/AddPlaylistRes/" + res.value + '/' + url);
      req.send(null);
   }
   if(opt == 2)
   {
      var req = new XMLHttpRequest();
      req.open("GET","api/AddChannelRes/" + res.value + '/' + url);
      req.send(null);
   }
   if(opt == 3)
   {
      var req = new XMLHttpRequest();
         req.open("GET","api/AddUserRes/" + res.value + '/' + url);
         req.send(null);
          
   }         
        
    

});
function yturl(url){
   if(url.length == 11)
   {
      return url;
   }
   var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;

   url = (decodeURIComponent(url));
   return (url.match(p)) ? RegExp.$1 : false ;
   
}

function play_video()
{
   let url =yturl(urlField.value);
   let resval=parseInt(res.value);
   let v = "";
   if(resval == 0)
   {
      v = "Converted";
   }
   if(resval == 1)
   {
      v="NotConverted";
   }
   if(resval == 2)
   {
      v="Audio";
   }
   // "api/Storage/File/" + v + '/' + url + ".mp4"

   window.open("api/Storage/File/" + v + '/' + url + ".mp4");
}
setInterval(progress2page, 3000); 
