{%include "libs.html" %}
<script>
    var oauth2  = {popup:null,}
    oauth2.listen = function (){
        oauth2._handler = setInterval (()=>{
          try{
            // console.log(oauth2.popup.location.href.match(/code=/) != null )
            if (oauth2.popup.closed){
                if (oauth2.popup.sessionStorage.redirect) {
                    if (oauth2._handler){
                        clearInterval(oauth2._handler)
                    }
                    window.open(oauth2.popup.sessionStorage.redirect,'_self')
                }
                
                
                
            }
          }catch(e){
            console.log(e)
            if (oauth2._handler){
                clearInterval(oauth2._handler)
            }
            
            
          }
        },1500);
    }
    oauth2.init = function (){
        var uri = ([qcms.context,'api/oauth2/authorize']).join('/')
        var http = HttpClient.instance()
        http.post(uri,(x)=>{
            if(x.status == 200 && x.readyState == 4){
                _data = JSON.parse(x.responseText)
                $('.qcms-login-buttons .provider').html(_data.label)
                $('.qcms-login').attr('data',_data.url)
            }
        })
    }
    oauth2.login = function (){
        var url = $('.qcms-login').attr('data')
        oauth2.popup = window.open(url, 'oauth', 'width=405, height=900')		
        oauth2.popup.focus()
        oauth2.listen()
        //
        // @TODO: add a listener

    }
    $(document).ready(()=>{
        oauth2.init()
    })
</script>
<div class="qcms-login">
    <div class="header">
        <img src="{{system.icon}}"/>
        <div>
            {{layout.header.title}}
        </div>
    </div>
    <div class="qcms-login-input">
        <ul style=";">
            <div style="margin:2px"><i class="fa-solid fa-minus"></i> Login using an account</div>
            <div style="margin:2px"><i class="fa-solid fa-minus"></i> An authetnication window will pop-out</div>

        </ul>
    </div>
    <div class="qcms-login-buttons" style="display:block">
        <div class="border-round border" onclick="oauth2.login()"><div class="active"><i class="fa-solid fa-check" style="color:green"></i> <span class="provider bold"></span> </div></div>
    </div>

</div>
