/*
 * MojeidConnect 2.0.0 (c) 2015-2019
 */
/*
Copyright (c) 2015-2017, CZ.NIC, z.s.p.o. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * @namespace
 * @function createMojeidConnect
 * @returns {Object} MojeidConnect instance
 */
var createMojeidConnect = (function() {

    var windowReadsMessage = false;
    var popupWindow = null;
    var defaultClientIdName = "clientId";

    /**
     * Call ajax POST with customizable url, callback, post data, headers and meantime function.
     * Call meantime function right before sending request. Callback is called when ready state reaches 4. Don't handle end of meantime function.
     *
     * @private
     * @param {String} url
     * @param {Function(xhr)} callback
     * @param {Function(xhr)} error_callback
     * @param {Object?} opt_postData
     * @param {Object?} opt_headers
     * @param {Function(xhr)?} opt_meanTime
     * @returns {undefined}
     */
    function ajax(url, callback, error_callback, opt_postData, opt_headers, opt_meanTime) {
        var headers = opt_headers || {
        };
        var postData = opt_postData || {
        };
        var xhr = new XMLHttpRequest();
        xhr.onerror = error_callback;
        xhr.open('POST', url);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                callback.call(this, xhr);
            }
        };
        for (var key in headers) {
            xhr.setRequestHeader(key, headers[key]);
        }
        var postString = "";
        for (var key in postData) {
            postString += key + "=" + postData[key] + "&";
        }

        if (opt_meanTime) {
            opt_meanTime(xhr);
        }
        xhr.send(postString);
    }

    /**
     * Reads url hash fragment and parse it into object.
     *
     * @private
     * @param {String} Hash fragment
     * @returns {Object} Parsed hash fragment values.
     */
    function getHashParams(opt_hash) {

        var hashParams = {
        };
        var e,
            regex = /([^&;=]+)=?([^&;]*)/g,
            hash = opt_hash || window.location.hash;

        if (hash.charAt(0) === '#') {
            hash = hash.substring(1);
        }
        while (e = regex.exec(hash)) {
            hashParams[decodeURIComponent(e[1])] = decodeURIComponent(e[2]);
        };
        return hashParams;
    }

    /**
     * Generate nonce
     *
     * @private
     * @returns {String}
     */
    function generateNonce() {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        var randomString = 'n-';
        for (var i=0; i<16; i++) {
            var num = Math.floor(Math.random() * chars.length);
            randomString += chars[num];
        }
        return randomString;
    }

    /**
     * @private
     * @param {Object} xhr
     * @returns {undefined}
     */
    function registrationCallback(xhr) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200 || xhr.status === 201) {
                var response = JSON.parse(xhr.responseText);
                this.clientId = response['client_id'];
                if (this.clientId) {
                    sessionStorage.setItem(this.clientIdName, response['client_id']);
                    console.log('Registration of the client succeeded. clientId("' + this.clientIdName + '") is', response['client_id']);
                    this.callbacks['registrationSuccessCallback'].call(this);
                } else {
                    console.log('Registration of the client failed.');
                    this.callbacks['registrationFailureCallback'].call(this);
                }
            } else {
                console.log('Registration of the client failed.');
                this.callbacks['registrationFailureCallback'].call(this);
            }
        }
    }

    /**
     * Return list of claims.
     *
     * @private
     * @param {Object} clientClaims
     */
    function parseClaims(clientClaims) {
        var claims = {};
        for (var cl in clientClaims) {
            claims[clientClaims[cl]] = {'essential': true};
        }
        return claims;
    }

    /**
     * Fills the form using the UserInfo and mapping between attribute and ElementId
     *
     * @private
     * @param {Dict} UserInfo
     */
    function fillForm(uiDict) {
        for (var key in uiDict) {
            var input = document.getElementById(this.attrDict[key] || key);
            if (input) {
                this.setValueToElements([input], this.decodeValue(uiDict[key]));
            }
        }
    }

    /**
     *
     * @private
     * @param {Object} event
     * @returns {undefined}
     */
    function incomingMessage(event) {
        if (event.origin == location.origin) {
            var uiDict = this.parseToken(event.data);
            this.callbacks['formCallback'].call(this, uiDict);
        }
    }

    /**
     * MojeID Connect library interface holder.
     *
     * @class MojeidConnect
     * @lends createMojeidConnect
     * @global
     * @param {Function(boolean)?} opt_registrationCallback
     * @param {Function(boolean)?} opt_formCallback
     * @param {Dict} opt_attrDict
     */
    function MojeidConnect(options) {
        this.init.apply(this, arguments);
    }

    /**
     * This is public library API.
     *
     */
    MojeidConnect.prototype = {
        /**
         * Initalize standart url endpoints, redirect uri based on origin and also sets custom callbacks if any.
         *
         * @constructs
         * @private
         * @param {Dict} options
         */
        init: function(options) {
            this.callbacks = {
                registrationCallback: registrationCallback,
                parseClaimsCallback: options['parseClaimsCallback'] || parseClaims,
                formCallback: options['formCallback'] || fillForm,
                registrationSuccessCallback: options['registrationSuccessCallback'] || function () {},
                registrationFailureCallback: options['registrationFailureCallback'] || function () {}
            };
            this.attrDict = options['attrDict'] || {
            };
            this.urlSetup = {
                "registration-endpoint": options['regEndpoint'] || "https://mojeid.cz/oidc/registration/",
                "authorization-endpoint": options['authEndpoint'] || "https://mojeid.cz/oidc/authorization/",
                "client-authorization-redirect-uri": options["redirectUri"] || location.origin + location.pathname,
            };
            this.clientName = options['clientName'] || location.origin
            this.display = options['display'] || 'popup'
            this.scope = options['scope'] || ['openid']
            // Make sure that openid is in scopes
            if (this.scope.indexOf('openid') == -1) {
                this.scope.push('openid')
            };
            this.claims = options['claims'] || undefined
            this.clientIdName = options['clientIdName'] || defaultClientIdName
            this.clientId = options['clientId']
            if (options['registerClientManualy'] !== true) {
                if (options['runRegisterInsideListener']) {
                    var mojeID = this;
                    document.addEventListener(options['runRegisterInsideListener'], function() {
                        if (mojeID.loadRSALibrary()) {
                            mojeID.registerClient()
                        }
                    })
                } else {
                    if (this.loadRSALibrary()) {
                        this.registerClient()
                    }
                }
            }
        },
        /**
         * Register client to provider. Client need clientID to identify himself.
         *
         * @returns {Boolean} True if function didnt fail and async request was called.
         */
        register: function() {
            var url = this.urlSetup["registration-endpoint"];
            var callback = this.callbacks['registrationCallback'];
            var postData = {
                "application_type": "web",
                "request_object_signing_alg": "RS256",
                "redirect_uris": [
                    this.urlSetup["client-authorization-redirect-uri"]
                ],
                "response_types": [
                    "id_token"
                ],
                "client_name": this.clientName
            };

            ajax(url, callback.bind(this), this.callbacks['registrationFailureCallback'].bind(this), postData);
            return true;
        },
        /**
         * Start user authorization proccess. Callback return access token if proccess pass.
         *
         * @param {String[]} scope Acceptable requested values are: "openid" (required), "profile", "address", "phone"
         * @param {String[]} claims Separate list of claims - see OpenID Connect specification for list of allowed claims
         * @param {String} display Options: popup (default), redirect
         * @returns {Boolean} True if function didnt fail and new window with registration is opened.
         */
        requestAuthentication: function() {
            // TODO implement meantime functions
            // meantime();
            var responseType = [
                "id_token"
            ];
            var parsedResponseType = responseType.join(" ");
            var parsedScope = this.scope.join(" ");

            var nonce = generateNonce();
            sessionStorage.setItem('nonce', nonce);

            var requestData = {
                "response_type": parsedResponseType,
                "scope": parsedScope,
                "client_id": this.clientId,
                "redirect_uri": this.urlSetup["client-authorization-redirect-uri"],
                "nonce": nonce,
            };

            if (this.claims) {
                var claims = {
                    "id_token": {
                    }
                }
                claims['id_token'] = this.callbacks['parseClaimsCallback'].call(this, this.claims);
                requestData["claims"] = JSON.stringify(claims);
            }


            var queryString = this.urlSetup["authorization-endpoint"] + "?";
            for (var key in requestData) {
                queryString += encodeURIComponent(key) + "=" + encodeURIComponent(requestData[key]) + "&";
            }

            if (this.display == 'popup') {
                if (!windowReadsMessage) {
                    window.addEventListener("message", incomingMessage.bind(this), false);
                    windowReadsMessage = true;
                }
                // window resolution is 850px * 550px
                var w = 850,
                    h = 550;
                var l = (screen.width - w) / 2,
                    t = (screen.height - h) / 2;
                popupWindow = window.open(queryString, "mojeID", "width=" + w + ",height=" + h + ",toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=" + t + ",left=" + l + "");
                popupWindow.focus();
            } else {
                window.top.location.assign(queryString);
            }
            return true;
        },

        /**
         * Set value to elements.
         *
         * @param {List} nodes
         * @param {String} value
         */
        setValueToElements: function (nodes, value) {
            for(var i=0; i < nodes.length; i++) {
                var input = nodes[i];
                if (input.type === "radio") {
                    if (input.value === value) {
                        input.checked = true;
                    }
                } else {
                    input.value = value;
                }
            }
        },

        /**
         * Parse formatted value
         *
         * @param {Object} value
         */
        decodeValue: function (value) {
            if (typeof(value) === "object") {
                if ('formatted' in value) {
                    value = value['formatted'];
                } else {
                    var content = [];
                    for (var k in value) {
                        content.push(k + ": " + value[k]);
                    }
                    value = content.join("\n");
                }
            }
            return value;
        },

        /**
         * Parse and verify id_token
         *
         * @param {String} hash part of the url
         * @return {Dict} parsed UserInfo
         */
        parseToken: function(opt_hash) {
            if (window.opener) {
                window.opener.postMessage(location.hash, location.origin)
                window.close()
            }
            if (location.hash || opt_hash) {
                var jws = new KJUR.jws.JWS();
                jws.parseJWS(getHashParams(opt_hash || location.hash)['id_token']);
                window.location.hash = '';
                var uiDict = JSON.parse(jws.parsedJWS['payloadS']);
                // Check nonce against stored in session and remove it prevent replay attacks
                var nonce = sessionStorage.getItem('nonce');
                sessionStorage.removeItem('nonce');
                if (uiDict['nonce'] == nonce) {
                    return uiDict;
                } else {
                    console.log('Nonce is not the same!');
                }
            }
        },

        /**
         * Load script JS RSA sign library.
         * @returns {Boolean} True if library was loaded.
         */
        loadRSALibrary: function () {
            var node = document.getElementById("mojeid-connect-script");
            if (node) {
                var jsrsasign = node.dataset.jsrsasign;
                if (jsrsasign) {
                    var mojeID = this;
                    var script = document.createElement('script');
                    script.src = jsrsasign;
                    // Make sure the script is loaded before we use it
                    script.onload = (function() {
                        var uiDict = mojeID.parseToken();
                        mojeID.callbacks['formCallback'].call(mojeID, uiDict);
                    });
                    document.querySelector("head").appendChild(script);
                    return true;
                } else {
                    console.error('Path to script "JS RSA Sign Library" was not found.')
                    this.callbacks['registrationFailureCallback'].call(this);
                }
            } else {
                console.log('Element #mojeid-connect-script was not found. It must load "JS RSA Sign Library" maually.');
            }
            return false;
        },

        /**
         * Register client if ID is not set.
         *
         */
        registerClient: function () {
            if (this.clientId) {
                this.callbacks['registrationSuccessCallback'].call(this);
            } else {
                this.register();
            }
        }

    };

    return function(options) {
        var clientIdName = options['clientIdName'] || defaultClientIdName
        if (!options['clientId'] && sessionStorage.getItem(clientIdName)) {
            options['clientId'] = sessionStorage.getItem(clientIdName)
            console.log('clientId("' + clientIdName + '") is ' + options['clientId'])
        }
        return new MojeidConnect(options);
    }

})();
