class CCPInfrastructureList extends HTMLElement{
#boot;
#socket;
#interval = null;
#infrastructures;
#rootdoc;
#style = `
`;
#serviceurl;
#broadcasturl;
constructor(){
super()
this.#boot = document.querySelector("d4s-boot-2")
this.#serviceurl = this.getAttribute("serviceurl")
this.#broadcasturl = this.getAttribute("broadcasturl")
if(!this.#broadcasturl){
this.#broadcasturl = this.#serviceurl.replace(/^http/, "ws")
}
this.#broadcasturl = this.#broadcasturl + "/ws/notification"
this.#rootdoc = this.attachShadow({ "mode" : "open"})
}
connectedCallback(){
this.connectBroadcast()
this.fetchInfrastructures()
}
fetchInfrastructures(){
const prom1 = this.#boot.secureFetch(this.#serviceurl + "/infrastructures").
then(resp=>{
if(resp.status !== 200) throw "Unable to fetch infrastructure cache";
return resp.json()
}).then(data=>{
this.#infrastructures = data
this.showList()
}).catch(err=>{
alert(err)
})
}
refreshInfrastructures(){
this.#boot.secureFetch(this.#serviceurl + "/infrastructures", { method : "HEAD"})
}
showList(){
if(this.getAttribute("render") !== "true") {
this.#rootdoc.innerHTML = ""
return;
}
this.#rootdoc.innerHTML = `
${this.#style}
${this.showInfrastructures()}
`
this.#rootdoc.querySelector(".ccp-infrastructure-toolbar").addEventListener("click", ev=>{
const evname = ev.target.getAttribute("name")
switch(evname){
case "refresh":
this.refreshInfrastructures();
break;
}
})
}
showInfrastructures(){
return this.#infrastructures.map(i => {
return `
${i.name}
${this.showAge(i)}
${this.showType(i)}
`
}).join("\n")
}
showAge(infra){
const age = Math.floor(((new Date()) - (new Date(infra.date))) / 3600000)
var cls = "badge-success"
var agetext = "fresh"
if(age > 24){
cls = "badge-warning";
agetext = "aged"
} else if (age > 72){
cls = "badge-secondary"
agetext = "old"
}
return `${agetext}`
}
showType(infra){
const t = infra.type.match(/docker/i) ? "docker" : null
const t2 = !t && infra.type.match(/lxd/i) ? "lxd" : t
return `${infra.type}`
}
connectBroadcast(){
this.#socket = new WebSocket(this.#broadcasturl + "/infrastructures");
this.#socket.onmessage = event=>{
this.fetchInfrastructures()
}
this.#interval = window.setInterval( ()=>{
if(this.#socket.readyState === 3){
this.#socket.close()
window.clearInterval(this.#interval)
this.connectBroadcast()
}else{
this.#socket.send("ping")
}
}, 30000)
}
}
window.customElements.define('d4s-ccp-infrastructurelist', CCPInfrastructureList);