/*
* Copyright (c) 2021 Xilinx, Inc.
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
* the following conditions: 
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software. 
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* 
*
*
*/
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
import './shared-styles.js';
import '@polymer/paper-button/paper-button';
import '@polymer/paper-input/paper-input';

class Login extends PolymerElement {
    static get template() {
        return html`
        <style include="shared-styles">
            :host {
                display: block;
                height: 100%;
            }
            .loginBlk {
                width: 25em;
                margin: 0px;
                padding: 0px;
                height: 18em;
            }
            .dFlexProp {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100%;
            }
            .headerLogin {
                background-color: rgba(0,0,0,0.3);
                padding: 15px;
                text-align: center;
            }
            .loginDetails {
                padding: 15px;
            }
            .loginDetails::after{
                content: '';
                display: block;
                clear: both;
            }
            .loginBtn {
                padding: 4px 8px;
                background-color: #1E88E5;
                color: #fff;
                height: 2em;
                font-size: 14px;
                font-weight: bold;
                text-align: center;
                float: right;
                margin-top: 1.2em;
            }
            h2 {
                margin-top: 10px;
                margin-bottom: 0px;
                color: #fff;
            }
            .logo {
                height: 3em;
                vertical-align: middle;
            }
            .errorMsg {
                color: #ee3626;
                font-size: 12px;
                font-weight: bold;
            }
        </style>
        <div class="dFlexProp">
            <div class="card loginBlk">
                <div class="headerLogin">
                    <img src="../images/logoXilinx.png" alt="Logo" class="logo" />
                </div>
                <div class="loginDetails">
                    <paper-input id="username" value={{userName}} label="Username" required auto-validate always-float-label name="username" type="text"></paper-input>
                    <paper-input id="password" value={{passVal}} label="Password" required auto-validate always-float-label name="password" type="password"></paper-input>
                    <span class="errorMsg" id="errorBlk" hidden={{invalidCred}}>Invalid credentials</span>
                    <paper-button class="loginBtn" on-tap="_login" raised noink>Login</paper-input>
                </div>
            </div>
        </div>
        <iron-ajax id="configdatabase" method="get" url=[[versionurl]] handle-as="json" content-type="application/json" last-response="{{lastResponse}}" on-error="_handleErrorResponse"></iron-ajax>
        <iron-ajax
        id="userLogin"
        method="POST"
        content-type="application/json"
        handle-as="json"
        debounce-duration="300">
        </iron-ajax>
    `;
    }
    static get properties() {
        return {
            url: {
                type: String,
                value: MyAppGlobals.serverUrl
            },
            userName: {
                type: String,
                value: ''
            },
            passVal: {
                type: String,
                value: ''
            },
            formData: {
                type: Object,
                value: {}
            },
            invalidCred: {
                type: Boolean,
                value: true
            },
            versionurl:{
                type: String,
                value: MyAppGlobals.serverUrl + 'getVersion'
            }
        };
    }

    ready() {
        super.ready();
        document.querySelector("#pageloader").style.display = "none";
        let self = this;
        this.$.password.addEventListener("keyup", function(event) {
            event.preventDefault();
            if (event.keyCode === 13) {
                self._login();
            }
        });
    }

    _login() {
        const userName = this.$.username.validate();
        const pass = this.$.password.validate();
        const _self = this;
        if (userName && pass) {
            this.formData = {
                username: this.userName,
                password: this.passVal,
                is_connected: navigator.onLine
            };
            this.$.userLogin.body = JSON.stringify(this.formData);
            this.$.userLogin.url = this.url + "login/";
            let request = this.$.userLogin.generateRequest();
            request.completes.then((req) => {
                let sUser = req.response;
                _self.$.configdatabase.headers['uid'] = request.xhr.getResponseHeader('uid');
                let versionrequest = _self.$.configdatabase.generateRequest();
                versionrequest.completes.then((req) => {
                    let dblist = req.response
                    sUser.versionarray = dblist;
                    sUser.version = dblist[0];
                    if (!sUser.hasOwnProperty('error')) {
                        this.invalidCred = true;
                        const url_string = window.location.href;
                        const url = new URL(url_string);
                        const name = url.searchParams.get("hostname");
                        const port = url.searchParams.get("port");
                        if (name && port) {
                            localStorage.setItem('hostname', name);
                            localStorage.setItem('port', port);
                        }
                        sUser.loggedin = true;
                        sUser.uid = request.xhr.getResponseHeader('uid');
                        _self.dispatchEvent(new CustomEvent('loginSuccessful', { bubbles: true, composed: true, detail: sUser }));
                        window.history.pushState({}, null, '/xregv');
                        window.dispatchEvent(new CustomEvent('location-changed'));
                        window.location.reload();
                        _self.$.username.value = "";
                        _self.$.password.value = "";
                    } else {
                        _self.invalidCred = false;
                        alert(sUser.error);
                    }
                }, () => {
                    if (request.status == 400)
                    redirectToLogin();
                });
            }, () => {
                if (request.response && request.response.error) {
                    alert(request.response.error);
                }
            });

        }
    }
}

window.customElements.define('login-view', Login);