let create= (x)=> document.createElement(x),
select= (x,y=document)=> y.querySelector(x),
selectAll= (x,y=document)=> y.querySelectorAll(x);
	
function getSrc(doc){
let player= [...selectAll("#player",doc)].at(-1);
if(player){
let script= player.nextElementSibling.innerHTML;
let src= script.match(/(?<=file\:").+(?=", autoplay)/);
return src[0].split(" or ");
}
else{
let audio= select("#myaudio",doc);
if(!audio) return [];
return [...selectAll("source",audio)].map(i=> i.src);
}
}


//when no audio foundz try to add to errors !!

function checkKey(key){
while(radiolist[key]){
key= key + "⚠️";
}
return key;
}



let errors= {};
let counter= 0;
let radiolist= {};

let allStations= selectAll("a p");
allStations.forEach(i=>{
let failed= false;
let url= i.closest("a").href;
fetch(url)
.then(r=> r.clone().json().catch(()=>r.text()))
.catch(f=>{
errors[url]= "Failed to fetch";
failed= true;
})
.then(d=>{
if(!failed){
let doc= new DOMParser().parseFromString(d,"text/html");
let name= select("h2",doc);
if(name) radiolist[checkKey(name.innerHTML)]= getSrc(doc);
else errors[checkKey(url)]= "Couldn't find property";
}
counter++;
})
.catch(x=> errors[url]= x);
});


//OPEN IN NEW TAB ------
function newTab(txt){
let a= create("textarea");
a.value= txt;
a.style.cssText= `width:98vw; height: 150vw;
border: 2px solid black; margin: 0;
padding: 10px; font: 14px Arial`;
window.open().document.body.append(a);
}


//SORT OBJECT -----
function sortObject(obj){
let result= Object.keys(obj);
result= result.sort((a,b)=>a>b ? 1:-1);
result= result.reduce((a,b)=>{
a[b]= obj[b];
return a;
},{});
 
return JSON.stringify(result,null," ");
}


let max= allStations.length;
let done= setInterval(()=>{
if(counter>=max){
clearInterval(done);
newTab(`SUCCESS: ${Object.keys(radiolist).length}/${max}--------
${sortObject(radiolist)}

ERRORS: ${Object.keys(errors).length}/${max}------------
${sortObject(errors)}
`);
}
},1000);





//https://securestreams7.autopo.st/?uri=
//https://api.codetabs.com/v1/proxy?quest=
//https://radiomixer.net/proxy?stream=
//https://www.liveradio.es/
