settings = {
    defaultPage: "home",
    showThumbnails: true,
    load: function()
    {
        var data=localStorage.getItem('settings');
        if(data != null)
        {
            cloneObject(settings,JSON.parse(data));
        }
        
    },
    save: function()
    {
        localStorage.setItem('settings', JSON.stringify(settings));

    }
};
function cloneObject(target, source) {
    if (!source || !target || typeof source !== "object" || typeof target !== "object")
        throw new TypeError("Invalid argument");

    for (var p in source)
        if (source.hasOwnProperty(p))
            if (source[p] && typeof source[p] === "object")
                if (target[p] && typeof target[p] === "object")
                    cloneObject(target[p], source[p]);
                else
                    target[p] = source[p];
            else 
                target[p] = source[p];
}
const app= {
    
    pages: [],
    show: new Event('show'),
    init: function()
    {
        myModal = new bootstrap.Modal(document.getElementById('modal1'));
        settings.load();
        var starting_page_name = settings.defaultPage;
        const enable_thumb= document.getElementById("enable_thumbnails");
        
      
        enable_thumb.checked=settings.showThumbnails;
        enable_thumb.addEventListener('input',(item)=>{
            settings.showThumbnails=item.target.checked;
            settings.save();
        });
        
        const starting_page = document.getElementById("starting_page");
        app.pages = document.querySelectorAll('.page');
        app.pages.forEach((pg) =>{
            pg.addEventListener('show',app.pageShown);
        })
        document.getElementById(starting_page_name).classList.add('active');
        document.querySelectorAll('.spalnk').forEach((link)=> {
            link.addEventListener('click', app.nav);
            var pageOption = document.createElement("option");
            starting_page.appendChild(pageOption);
            var pageLink = link.getAttribute('data-target');
            var pageName = link.innerText;
            if(pageName == "Tesses YouTube Downloader")
            {
                pageName = "Home";
            }
            pageOption.innerText = pageName;
            pageOption.value = pageLink;
            if(pageLink == settings.defaultPage)
            {
               
                history.replaceState({},pageName,'#' + pageLink);
              
            }
            
            
        })
        starting_page.addEventListener('input',(event)=>{
            settings.defaultPage=event.target.value;
            settings.save();
        })
        starting_page.value=settings.defaultPage;
        window.addEventListener('popstate',app.poppin);
        if(settings.defaultPage == 'videos')
        {
            list_videos();
        }
        if(settings.defaultPage == 'playlists')
        {
            list_playlists();
        }
    },
    nav: function(ev) {
        ev.preventDefault();
        let currentPage = ev.target.getAttribute('data-target');
        document.querySelector('.active').classList.remove('active');
        document.getElementById(currentPage).classList.add('active');
        console.log(currentPage);
        history.pushState({},currentPage,`#${currentPage}`)
        document.getElementById(currentPage).dispatchEvent(app.show);
    },
    pageShown: function(ev)
    {
        let hash=location.hash.replace('#','');

        if(hash == 'videos')
        {
            list_videos();
        }
        if(hash == 'playlists')
        {
            list_playlists();
        }
       
    },
    poppin: function(ev)
    {
        let hash=location.hash.replace('#','');
        let currentPage = ev.target.getAttribute('data-target');
        document.querySelector('.active').classList.remove('active');
        document.getElementById(hash).classList.add('active');
        console.log(hash);
       // history.pushState({},currentPage,`#${currentPage}`)
        document.getElementById(currentPage).dispatchEvent(app.show);
    }
}
function get_view_count(views)
{
    if(views > 1000000000)
    {
        
        return Math.round(views/1000000000).toString() + "B";
    }
    if(views > 1000000)
    {
        
        return Math.round(views/1000000).toString() + "M";
    }
    if(views > 1000)
    {
        
        return Math.round(views/1000).toString() + "K";
    }
    return views.toString();
}
function removeAllChildNodes(parent) {
    while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
    }
}
function add_playlist(vid_list,item)
{
    
    var vid_template = document.getElementById("video_template");
    var xmlhttp2 = new XMLHttpRequest();
                xmlhttp2.onreadystatechange = function() {
                  if (this.readyState == 4 && this.status == 200) {
                    var myData2 = JSON.parse(this.responseText);
                        //this is a video
                        var id = myData2.Id;
                        var title=myData2.Title;
                        var author = myData2.AuthorTitle;
                        var views = myData2.Videos.length.toString() + " Videos";
                        
                        

                        var video_element = vid_template.content.cloneNode(true);
                        var video_link=video_element.querySelector(".video_link");
                        video_link.innerText = title;
                        video_link.href="#";
                        video_link.setAttribute('data-id',id);
                        video_link.addEventListener("click",(evt)=>{
                            evt.preventDefault();
                           
                            document.querySelector('.active').classList.remove('active');
                            document.getElementById('view_videos_list').classList.add('active');
                            console.log('view_videos_list');
                            history.pushState({},'view_videos_list','#view_videos_list');
                            document.getElementById('view_videos_list').dispatchEvent(app.show);
                            list_playlist(evt.target.getAttribute('data-id'));
                        })
                        var video_thumbnail=video_element.querySelector(".image");
                        if(settings.showThumbnails){
                            if(myData2.videos.length > 0){
                            video_thumbnail.setAttribute("src","api/Storage/File/Thumbnails/168x94/" + myData2.Videos[0] + ".jpg");
                            }
                        }
                        var video_views = video_element.querySelector(".views");
                        video_views.innerText = views;
                        var video_author = video_element.querySelector(".video_author");
                        video_author.innerText = author;
                        
                        vid_list.appendChild(video_element);
                       
                  }
                };
                xmlhttp2.open("GET", "api/Storage/File/Playlist/" + item, true);
                xmlhttp2.send();
}
function list_playlist(id)
{
    console.log(id);
    console.log("list_playlist");
    var xmlhttp = new XMLHttpRequest();
    var vid_list= document.getElementById("videos_list_view");
    
    removeAllChildNodes(vid_list);


    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          console.log("got /api/Storage/GetFiles/Playlist");
        var myData = JSON.parse(this.responseText);
            myData.Videos.forEach((item)=>{
                try {
                    add_video(vid_list,item + '.json');
                } catch (error) {
                    
                }
                
            });
          
       }
       
    };
    xmlhttp.open("GET", "api/Storage/File/Playlist/" + id + ".json", true);
    xmlhttp.send();
}

function close_modal()
{
    myModal.hide();
}

function list_playlists()
{
    console.log("list_playlist");
    var xmlhttp = new XMLHttpRequest();
    var vid_list= document.getElementById("playlists_list");
    
    try{
    removeAllChildNodes(vid_list);
    }catch(er)
    {

    }

    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          console.log("got /api/Storage/GetFiles/Playlist");
        var myData = JSON.parse(this.responseText);
            myData.forEach((item)=>{
                add_playlist(vid_list,item);
            });
          
       }
       
    };
    xmlhttp.open("GET", "api/Storage/GetFiles/Playlist", true);
    xmlhttp.send();
}
var myModal;
var vtitle_modal;
function video_dialog_show(id,title)
{
    const vid = document.getElementById('video_id_modal');
    const vtitle = document.getElementById('video_title_modal');
    vid.value = id;
    vtitle.innerText=title;
    vtitle_modal=title;
    
    myModal.show();
 
}
function play()
{
    const rbs = document.querySelectorAll('input[name="res"]');
            let selectedValue;
            for (const rb of rbs) {
                if (rb.checked) {
                    selectedValue = rb.value;
                    break;
                }
            }
            const vid = document.getElementById('video_id_modal');
            
            var ar = ["Converted","NotConverted","Audio"];
           
            window.open('/api/Storage/File/' + ar[parseInt(selectedValue)] + '/' + vid.value + '.mp4',
            vtitle_modal,
            "resizable,scrollbars"
          );
            close_modal();
}
function download()
{
    const rbs = document.querySelectorAll('input[name="res"]');
    let selectedValue;
    for (const rb of rbs) {
        if (rb.checked) {
            selectedValue = rb.value;
            break;
        }
    }
    const vid = document.getElementById('video_id_modal');
    window.open('/api/Storage/VideoRes/' + selectedValue + '/' + vid.value,'_blank');
    close_modal();
}
function add_video(vid_list,item)
{
    var vid_template = document.getElementById("video_template");
    var xmlhttp2 = new XMLHttpRequest();
                xmlhttp2.onreadystatechange = function() {
                  if (this.readyState == 4 && this.status == 200) {
                    var myData2 = JSON.parse(this.responseText);
                        //this is a video
                        var id = myData2.Id;
                        var title=myData2.Title;
                        var author = myData2.AuthorTitle;
                        var views = get_view_count(myData2.Views) + " Views";
                        var uploadDate= new Date(myData2.UploadDate);
                        let myVid=id;
                        let myTitle=title;

                        var video_element = vid_template.content.cloneNode(true);
                        var video_link=video_element.querySelector(".video_link");
                        video_link.innerText = title;

                        video_link.href="javascript:void";
                        video_link.addEventListener('click',(e)=>{
                            e.preventDefault();
                            video_dialog_show(myVid,myTitle);
                        });
                        var video_thumbnail=video_element.querySelector(".image");
                        if(settings.showThumbnails){
                            video_thumbnail.setAttribute("src","api/Storage/File/Thumbnails/168x94/" + id + ".jpg");
                            
                        }else{
                            //video_element.removeChild(video_thumbnail);
                        }
                        var video_views = video_element.querySelector(".views");
                        video_views.innerText = views;
                        var video_author = video_element.querySelector(".video_author");
                        video_author.innerText = author;
                        var video_date = video_element.querySelector(".date");
                        video_date.innerText = (uploadDate.getMonth() + 1).toString() + '/' + uploadDate.getDate().toString() + '/' + uploadDate.getFullYear().toString();

                        vid_list.appendChild(video_element);
                       
                  }
                };
                xmlhttp2.open("GET", "api/Storage/File/Info/" + item, true);
                xmlhttp2.send();
}
function list_videos()
{
    console.log("list_videos");
    var xmlhttp = new XMLHttpRequest();
    var vid_list= document.getElementById("videos_list");
    
    removeAllChildNodes(vid_list);


    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          console.log("got /api/Storage/GetFiles/Info");
        var myData = JSON.parse(this.responseText);
            myData.forEach((item)=>{
                add_video(vid_list,item);
            });
          
       }
       
    };
    xmlhttp.open("GET", "api/Storage/GetFiles/Info", true);
    xmlhttp.send();
}
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
      navigator.serviceWorker.register('sw.js').then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      }, function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
      });
    });
  }
document.addEventListener("DOMContentLoaded",app.init);
