let create= (x)=> document.createElement(x),
select= (x,y=document)=> y.querySelector(x),
selectAll= (x,y=document)=> y.querySelectorAll(x);


let hide= select("p.show.hide");
let prevGenre= select("span.left");
let nextGenre= select("span.right");
let pause= select("p.play.pause");
let timer= select(".block4");
let audio= select("audio");
let proxy= "https://cors.bitwize.com.lb/";
let offline= "https://kawiesh.tk/resources/kdradiosorry.mp3";
let mediaSession= ("mediaSession" in navigator);
let ignoreHS= false;

let genre= Object.keys(blocklist);
let index= 0;
//let hidden= (blocklist[genre[index]]!=[]);
let hidden= true;

//let localhidden= {};

//____________________________________________________________ BLOCK 1
hide.onclick= function(){
hideStations();
};


/*
let isSr= select("p.in");
let isBw= select("p.sr");



if(isSr){
isSr.onclick=()=> location= "bollywood.html";
}

if(isBw){
isBw.onclick=()=> location= "index.html";
}


*/


checkHash();
createStations(list[index]);
select("p.genre").style.visibility= (list.length>1) ? "visible" : "hidden";
	










/*
function hmm(){
let interval= setInterval(()=>{
if(audio.currentTime>0){
mediaControl(audio.title);
showControls();
clearInterval(interval);	
}	
},1000);	
}
*/











/*_______________________________________________________________________
														EVENT BINDING
_______________________________________________________________________*/


//Switching genres using location hash
window.onhashchange=()=>{
checkHash();
createStations(list[index]);
};




//Skip to previous genre
select("span.left").onclick=()=>{
index= (index<=0) ? list.length-1 : index-1;
createStations(list[index]);
};

//Skip to next genre
select("span.right").onclick=()=>{
index= (index<list.length-1) ? index+1 : 0;
createStations(list[index]);

}; 



//Play or pause radio
pause.onclick= function(){
if(audio.currentSrc==offline) return;
if(audio.currentTime<1) return;

if(audio.paused){
audio.play();
this.innerHTML= "PAUSE";
}
else{
audio.pause();
this.innerHTML= "PLAY";
}

};


//Update info when audio's playing
audio.ontimeupdate= function(){
let time= formatTime(this.currentTime*1000);
if(this.currentTime<1){
updatePage("clicked",time);
}
else{
if(!this.paused){
let klass= (this.currentSrc==offline) ? "offline" : "playing";
updatePage(klass,time);
}
else{
updatePage("paused",time);
}
}
};





//Skip to next/prev stations
select("p.prev").onclick=()=> ignoreHS ? 
skipVisibleStations("left") : skipAllStations("left");
select("p.next").onclick=()=> ignoreHS ? 
skipVisibleStations("right") : skipAllStations("right");




/*_______________________________________________________________________
													MAIN FUNCTION
_______________________________________________________________________*/
function createStations(obj){
select(".block2").innerHTML= "";	

Object.keys(obj).forEach((i,x)=>{
let p= create("p");
p.className= "station flexcenter";
p.dataset.hidden= "false";
p.innerHTML= checkProtocol(i,obj[i]);
select(".block2").append(p);	

p.onclick=()=>{
focusOnStation(p);
timer.innerHTML= `loading ${obj[i]}`;
audio.title= p.innerHTML;
audio.dataset.jan= checkProtocol(i,false);
audio.innerHTML= `<source src="${checkProtocol(i,false)}">
<source src="${offline}">`;
audio.load();
audio.play();
mediaControl(p.innerHTML);
};
});


select("span.middle").innerHTML=location.hash= genre[index];

if(currentStation()){
currentStation().className= "station flexcenter";
currentStation().classList.add(audio.className);
//mediaControl(currentStation().textContent);
}


hideStations();
}


/*_______________________________________________________________________
													HELPER FUNCTIONS
_______________________________________________________________________*/
//Modify station url and name if proxy needed
function checkProtocol(url,name){
if(location.protocol!="https:") return name ? name : url; 
if(url.startsWith("https:")) return name ? name : url;
return name ? `!${name}` : `${proxy}${url}`;
}


//Formatting stations 
function focusOnStation(station){
selectAll("p.station").forEach(i=>{
i.dataset.clicked= false;	
i.className= "station flexcenter";
});
//station.dataset.clicked= true;
station.classList.add("clicked");
}



//Check window hash
function checkHash(){
if(location.hash){
for(let i=0; i<genre.length; i++){
	if(location.hash.includes(genre[i])){
	index= i;
	break;
	}
}
}
}



//Show and hide stations
function hideStations(){
let allStations= selectAll("p.station");
let hidden= select(".station[data-hidden='true']") ? true : false;

allStations.forEach(i=> i.dataset.hidden= "false");

let arr= blocklist[genre[index]];
//let options= selectAll(".modal option");
let localblocklist= localStorage["localblocklist"];

if(localblocklist){
localblocklist= JSON.parse(localblocklist,null,1);
arr= localblocklist[genre[index]]||blocklist[genre[index]];
}

if(!hidden){
arr.forEach(i=>{
//options[i].selected= true;
allStations[i].dataset.hidden= "true";
});
hide.innerHTML= "ALL";
}
else hide.innerHTML= "FEW";


//restoreSelectedStations(arr);

//restoreHideButton();

//localhidden[genre[index]]= hidden;
}








function restoreHideButton(){
/*localhidden= localStorage["localhidden"];
if(localhidden){
localhidden= JSON.parse(localhidden,null,1);
hidden= localhidden[genre[index]]||hidden;
}*/

//localhidden[genre[index]]= hidden;
//localStorage["localhidden"]= JSON.stringify(localhidden);
if(hidden) select(".show.hide").click();
select("textarea").value= hidden;
}



//Updating timer and station info
function updatePage(klass,time){

switch(klass){
case "playing" : 
pause.innerHTML= "PAUSE";
//pause.style.pointerEvents= "auto";
document.title= `${audio.title} - KD Radio`;
timer.innerHTML= `Listening to ${audio.title} for ${time}`;
break;
case "paused" : 
pause.innerHTML= "PLAY";
//pause.style.pointerEvents= "auto";
document.title= `${audio.title} [Paused] - KD Radio`;
timer.innerHTML= `${audio.title} paused after ${time}`;
break;
case "offline" :
pause.innerHTML= "•&nbsp;•&nbsp;•";
//pause.style.pointerEvents= "none";
document.title= `${audio.title} [Offline] - KD Radio`;
timer.innerHTML= `${audio.title} is offline`;
break;
default:
pause.innerHTML= "•&nbsp;•&nbsp;•";
//pause.style.pointerEvents= "none";
document.title= `Loading ${audio.title}...`;
timer.innerHTML= `Loading ${audio.title}....`;
}


audio.className= klass;
if(currentStation()){
currentStation().className= "station flexcenter";
currentStation().classList.add(audio.className);
}

}



//find current station
function currentStation(){
let stations= selectAll("p.station");
for(let i=0; i<stations.length; i++){
if(stations[i].textContent==audio.title){
return stations[i];
}
}
return false;
}




//Format time 
function formatTime(time){
let hms= new Date(time).toISOString().substr(11,8).split(":");
let h= +hms[0], m= +hms[1], s= +hms[2];

let H= h;
let M= m;

switch(h){
case 0: H= ""; break;
case 1: H= "1 hour, "; break;
default:H= `${h} hours, `;
}

switch(m){
case 0: M= ""; break;
case 1: M= "1 min. & "; break;
default:M= `${m} min. & `;
}

return `${H}${M}${s} sec.`;

}




//Notification Pannel
function mediaControl(station){
if(!mediaSession) return;
navigator.mediaSession.setActionHandler('previoustrack',()=>{
ignoreHS ? skipAllStations("left") : skipVisibleStations("left");
});

navigator.mediaSession.setActionHandler('nexttrack',()=>{
ignoreHS ? skipAllStations("right") : skipVisibleStations("right");
});

navigator.mediaSession.metadata= new MediaMetadata({
title: station,
artist: "Kawiesh's Radio Collection",
album: `@ ${location.hostname} !`,
artwork: getArtwork([96,128,192,256,384,512])
});

}


function getArtwork(sizes){
let arr= [];
sizes.forEach(i=>{
let obj= {};
obj.sizes= `${i}x${i}`;
obj.type= `image/png`;
obj.src= `https://kawiesh.tk/resources/artwork/background-${i}x${i}.png`;
arr.push(obj);
});

return arr;
}



//Skip through all stations
function skipAllStations(direction){
if(audio.title=="") return;

if(currentStation()){

if(direction=="left"){
let last= select("p.station:last-child");
let prev= currentStation().previousElementSibling;
if(prev) prev.click(); else last.click();
}
else{
let first= select("p.station:first-child");
let next= currentStation().nextElementSibling;
if(next) next.click(); else first.click();
}

}
else{

stationGone();
skipAllStations(direction);
}	
	
}





//Skip through only visible stations
function skipVisibleStations(direction){
if(audio.title=="") return;
	
if(currentStation()){
let visibleStations= selectAll("p.station");
visibleStations= 
[...visibleStations].filter(i=> i.dataset.hidden=="false");

let first= visibleStations[0];
let last= visibleStations[visibleStations.length-1];

if(direction=="left"){
let prev= currentStation().previousElementSibling;
if(!prev) prev= last;
while(prev.dataset.hidden=="true"){
prev= prev.previousElementSibling;
}

prev.click();

}
else{
let next= currentStation().nextElementSibling;
if(!next) next= first;
while(next.dataset.hidden=="true"){
next= next.nextElementSibling;
}
next.click();
}

}
else{
stationGone();
skipStations(direction);
}	
	
}



//If current station is removed from DOM
function stationGone(){
for(let i=0; i<list.length; i++){

let a= Object.keys(list[i]);
for(let j=0; j<a.length; j++){
	if(audio.dataset.jan==a[j]){
	index= i;
	createStations(list[index]);
	return;
	}
}
	
}
}

