<%--
  Created by IntelliJ IDEA.
  User: sofia
  Date: 19/10/2017
  Time: 4:30 μμ
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en-gb" dir="ltr" vocab="http://schema.org/">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href=".">
    <title>OpenAIRE - Register</title>
    <script src="./js/jquery.js"></script>
    <script src="./js/uikit.min.js"></script>
    <script src="./js/uikit-icons-max.js"></script>
    <link rel="stylesheet" style="text/css" href="./css/theme.css">
    <link rel="stylesheet" style="text/css" href="./css/custom.css">
    <link rel="stylesheet" style="text/css" href="./css/aai-custom.css">
    <link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="images/favicon//favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png">
    <link href="images/favicon/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon"/>
</head>
<body class="" style="">
<div class="uk-offcanvas-content uk-height-viewport">
    <jsp:include page="header.jsp"/>
    <!-- CONTENT STARTS HERE -->
    <div class=" uk-section  uk-margin-small-top uk-container uk-container-large" id="tm-main">
        <div class="uk-grid ">
            <div class="uk-width-1-4@m">
                <div class="uk-card uk-card-default uk-card-body">
                    <div class="uk-h4">API Access</div>
                    <ul class="uk-nav uk-nav-default">
                        <li class=""><a href="./personalToken">Personal token</a></li>
                        <li class=""><a href="./registeredServices">Registered services</a></li>
                    </ul>
                </div>
            </div>
            <!-- CENTER SIDE -->
            <div class="uk-width-2-3@l uk-width-2-3@m">
                <c:choose>
                    <c:when test="${not empty param.id}">
                        <h4 class="uk-margin-remove-top uk-text-bold uk-text-primary">Edit service</h4>
                    </c:when>
                    <c:otherwise>
                      <h4 class="uk-margin-remove-top uk-text-bold uk-text-primary">Add a new service</h4>
                    </c:otherwise>
                </c:choose>

                <!-- REGISTER FORM -->
                <div id="registerForm">
                    <form action="registerService" method="POST" role="form" class="m-t uk-form-horizontal"
                          id="register_form">
                          <input type="hidden" name="id" value="${param.id}"/>
                        <c:choose>
                            <c:when test = "${not empty param.id}">
                                <input type="hidden" name="mode" value="edit"/>
                            </c:when>
                            <c:otherwise>
                              <input type="hidden" name="mode" value="create"/>
                            </c:otherwise>
                        </c:choose>
                        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                        <div class="alert alert-success" aria-hidden="true" style="display: none;"></div>
                        <div class="alert alert-danger" aria-hidden="true" style="display: none;"></div>
                        <div class="uk-margin-medium-top">
                            <label class="uk-form-label uk-text-bold" for="first_name">Name*</label>
                            <div class="uk-margin-small">Give a name to your service</div>
                            <input id="first_name" name="first_name" type="text" placeholder="Name (*)"
                                   class="uk-input ${first_name_error == true?'uk-form-danger':''}"
                                   onkeyup="validate()" onfocusout="nameTouched = true;validate()" value="${(first_name != null)?first_name:''}">
                            <c:choose>
                                <c:when test="${first_name_error == true}">
                                    <div id="first_name_error" class="uk-text-danger uk-text-small">Please enter a name for your service.
                                    </div>
                                </c:when>
                                <c:otherwise>
                                <div id="first_name_error" style="display:none;" class="uk-text-danger uk-text-small">Please enter a name for your service.</div>
                                </c:otherwise>
                            </c:choose>
                            <c:remove var="first_name" scope="session"/>
                            <c:remove var="first_name_error" scope="session"/>
                        </div>
                        <div class="uk-margin-medium-top">
                            <label class="uk-form-label uk-text-bold">Security level</label>
                            <div id="security-hint" class="uk-margin"></div>
                            <div class="uk-margin-small-top">
                                <span class="uk-margin-small-right">
                                    <input id="basic" class="uk-radio uk-margin-small-right" type="radio"
                                           name="security_level"
                                           value="basic" ${key_type == null ? 'checked' : ''}>
                                    <label class="clickable" for="by_value">Basic</label>
                                </span>
                                <span>
                                    <input id="advanced" class="uk-radio uk-margin-small-right" type="radio"
                                           name="security_level" value="advanced"  ${key_type != null ? 'checked' : ''}>
                                    <label class="clickable" for="by_uri">Advanced</label>
                                </span>
                            </div>
                        </div>
                        <div id="public-key" class="uk-margin-medium-top">
                            <label class="uk-form-label uk-text-bold">Public Key</label>
                            <span class="uk-float-right">
                                <span class="uk-margin-small-right">
                                    <input id="by_value" class="uk-radio uk-margin-small-right" type="radio"
                                           name="key_type"
                                           value="value" ${(key_type == 'value') ? 'checked' : ''}>
                                    <label class="clickable" for="by_value">By Value</label>
                                </span>
                                <span>
                                    <input id="by_uri" class="uk-radio uk-margin-small-right" type="radio"
                                           name="key_type"
                                           value="uri" ${key_type == 'uri' ? 'checked' : ''}>
                                    <label class="clickable" for="by_uri">By URI</label>
                                </span>
                            </span>
                            <c:remove var="key_type" scope="session"/>
                            <div class="uk-margin">Public Key hint</div>
                            <div id="value_input">
                                <textarea id="value" name="value" type="textarea"
                                          placeholder='{"kty": ..., "e": ... , "use": ... , "kid": ..., "alg": ... , "n": ...}'
                                          onfocusout="valueTouched = true;validate()"
                                          onkeyup="validate()"
                                          class="uk-textarea ${value_error == true?'uk-form-danger':''}" rows="10">${(value != null)?value:''}</textarea>
                                <c:choose>
                                    <c:when test="${value_error == true}">
                                        <div id="value_error" class="uk-text-danger uk-text-small">Please provide a valid JSON. The format should be
                                            {"kty": ..., "e": ... , "use": ... , "kid": ..., "alg": ... , "n": ...} </div>
                                        <c:remove var="value_error" scope="session"/>
                                    </c:when>
                                    <c:otherwise>
                                        <div id="value_error" style="display:none;" class="uk-text-danger uk-text-small">Please provide a valid JSON. The format should be
                                        {"kty": ..., "e": ... , "use": ... , "kid": ..., "alg": ... , "n": ...} </div>
                                    </c:otherwise>
                                </c:choose>
                                <c:remove var="value" scope="session"/>
                            </div>
                            <div id="uri_input" style="display:none;">
                                <input id="uri" name="uri" type="text" placeholder="https://" onfocusout="uriTouched = true;validate()"
                                       onkeyup="validate()"
                                       class="uk-input ${uri_error == true?'uk-form-danger':''}" value="${(jwksUri != null)?jwksUri:''}">
                                <c:choose>
                                    <c:when test="${uri_error == true}">
                                        <div id="uri_error"  class="uk-text-danger uk-text-small">
                                            Please provide a valid URI (do not forget the protocol! https://...)
                                        </div>
                                        <c:remove var="uri_error" scope="session"/>
                                    </c:when>
                                    <c:otherwise>
                                        <div id="uri_error" style="display:none;" class="uk-text-danger uk-text-small">
                                            Please provide a valid URI (do not forget the protocol! https://...)
                                        </div>
                                    </c:otherwise>
                                </c:choose>
                                <c:remove var="jwksUri" scope="session"/>
                            </div>
                        </div>
                        <div class="uk-flex uk-flex-right uk-margin-medium-top">
                            <a type="submit" class="uk-button uk-button-default uk-margin-small-right"
                               href="./registeredServices">Cancel</a>
                            <button id="create" type="submit" class="uk-button uk-button-primary" onclick="return validate();">
                                <c:choose>
                                    <c:when test="${not empty param.id}">
                                        Update service
                                    </c:when>
                                    <c:otherwise>
                                        Add new service
                                    </c:otherwise>
                                </c:choose>
                            </button>
                        </div>
                    </form>
                </div>
                <!-- END OF REGISTER FORM -->
                </ul>
            </div>
            <!-- END OF CENTER SIDE -->
        </div>
    </div>
    <!-- CONTENT ENDS HERE -->
    <c:import url="footer.jsp"/>
</div>
</body>
</html>
<script>
    var nameTouched = false;
    var valueTouched = false;
    var uriTouched = false;
    $(document).ready(function () {
        checkRadio();
        if($('input[name=mode]').val() === 'edit') {
            $("#basic").prop("disabled", true);
            $("#advanced").prop("disabled", true);
        }
        if($('#value_error').is(':visible')) {
            $("#value_input").get(0).scrollIntoView();
        } else if($('#uri_error').is(':visible')) {
            $("#uri_input").get(0).scrollIntoView();
        }
        $('input[type=radio][name=security_level]').change(function () {
            var securityLevel = $('input[type=radio][name=security_level]:checked').val();
            if(securityLevel === 'advanced') {
                $("#by_value").prop("checked", true);
            } else {
                $("#by_value").prop("checked", false);
                $("#by_uri").prop("checked", false);
            }
            checkRadio();
        });
        $('input[type=radio][name=key_type]').change(function () {
            checkRadio();
        });
    });

    function checkRadio() {
        var securityLevel = $('input[type=radio][name=security_level]:checked').val();
        if(securityLevel === 'basic') {
            $("#security-hint").html('Register your service to get a client id and a client secret. Use the client id and secret to make your requests. <a href="https://graph.openaire.eu/develop/basic.html" target="_blank">Read more...</a>');
            $("#public-key").hide();
        } else {
            $("#security-hint").html('Register your service to get a client id. Declare your public key and instead of using the client secret to make a request, send a client assertion (JWT) signed with your private key. <a href="https://graph.openaire.eu/develop/advanced.html" target="_blank">Read more...</a>');
            var keyType = $('input[type=radio][name=key_type]:checked').val();
            $("#public-key").show();
            if (keyType === 'uri') {
                $("#uri_input").show();
                $("#value_input").hide();
            } else if (keyType === 'value') {
                $("#uri_input").hide();
                $("#value_input").show();
            }
        }
        validate();
    }

    function validate() {
        var isValid = true;
        var create = $('#create');
        create.prop('disabled', true);
        var name = $("#first_name");

        if (name.val() !== undefined) {
            if ($.trim(name.val()).length <= 0) {
                if (nameTouched) {
                    name.addClass('uk-form-danger');
                    $("#first_name_error").show();
                }
                isValid = false;
            } else {
                if (nameTouched) {
                    name.removeClass('uk-form-danger');
                    $("#first_name_error").hide();
                }
            }
        }
        var securityLevel = $('input[type=radio][name=security_level]:checked').val();
        if(securityLevel === 'advanced') {
            var keyType = $('input[type=radio][name=key_type]:checked');
            if (keyType.val() === 'value') {
                if (!validateJSON()) {
                    if (valueTouched) {
                        $("#value").addClass('uk-form-danger');
                        $("#value_error").show();
                    }
                    isValid = false;
                } else {
                    if (valueTouched) {
                        $("#value").removeClass('uk-form-danger');
                        $("#value_error").hide();
                    }
                }
            }
            if (keyType.val() === 'uri') {
                if (!validateURI()) {
                    if (uriTouched) {
                        $("#uri").addClass('uk-form-danger');
                        $("#uri_error").show();
                    }
                    isValid = false;
                } else {
                    if (uriTouched) {
                        $("#uri").removeClass('uk-form-danger');
                        $("#uri_error").hide();
                    }
                }
            }
        }

        if (isValid) {
            create.prop('disabled', false);
        }
        return isValid;
    }

    function validateJSON() {
        var value = $("#value").val();
        if (value !== undefined && value !== "") {
            return /^[\],:{}\s]*$/.test(value.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
        }
        return false;
    }

    function validateURI() {
        var value = $("#uri").val();
        if (value !== undefined && value !== "") {
            return /^(?:(?:(?:https):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value);
        }
        return false;
    }
</script>