class ExtAppRoleController extends HTMLElement{
  
    #boot;
    #roles;
    #users;
    #mappings;
    #serviceurl;
    #appid;
    #loading = false;
    
    constructor(){
      super()
      this.#boot = document.querySelector("d4s-boot-2")
      this.#serviceurl = this.#boot.url
    }

    connectedCallback(){
      this.#appid = this.getAttribute("appid")
      if(!this.#loading){
        this.#loading = true
        this.loadData()
      }
    }
    
    loadData(){
        Promise.all([
            this.loadEligibleUsers(), this.loadRoles()
        ]).then(()=>{
            console.log("Done. Ui should be complete now")
        }).catch(err=>alert(err))
    }

    loadEligibleUsers(){
        const url = this.#serviceurl + `/admin/realms/d4science/clients/${this.#appid}/roles/eligible/users?briefRepresentation=true&max=-1&first=0`
        return this.#boot.secureFetch(url).then(resp=>{
            if(resp.ok){
                return resp.json()
            }else  if(resp.status === 403){
                throw "Fetching users: You are not allowed to manage roles for this application."
            }else{
                throw "Fetching users: Unspecified error"
            }
        }).then(json=>{
            console.log("Fetched eligible users can show table")
            this.#users = json
            return loadMappings()
        }).then(()=>{
            console.log(this.#mappings)
        })
    }

    loadRoles(){
        const url = this.#serviceurl + `/admin/realms/d4science/clients/${this.#appid}/roles`
        return this.#boot.secureFetch(url).then(resp=>{
            if(resp.ok){
                return resp.json()
            }else  if(resp.status === 403){
                throw "Fetching roles: You are not allowed to manage roles for this application."
            }else{
                throw "Fetching roles: Unspecified error"
            }
        }).then(json=>{
            this.#roles = json
            console.log("Roles loaded, could draw header")
        })
    }

    loadMappings(){
        return Promise.all(
            this.#users.forEach(u => {
                const url = this.#serviceurl + `/admin/realms/d4science/users/${u.id}/clients/${this.#appid}/roles`
                this.#boot.secureFetch(url).then(resp=>{
                    if(resp.ok){
                        return resp.json()
                    }else  if(resp.status === 403){
                        throw "Fetching role mappings: You are not allowed to manage roles for this application."
                    }else{
                        throw "Fetching role mappings: Unspecified error"
                    }
                }).then(json=>{
                    u.mappings = json
                    console.log(`Fetched mappings for user ${u.id} can update the proper table`)
                })
            })
        )
    }

}
  
window.customElements.define('d4s-extapp-role-manager', ExtAppRoleController);