<%--
 ~
 ~ Copyright (c) 2021, WSO2 Inc. (http://www.wso2.com). All Rights Reserved.
 ~
 ~ This software is the property of WSO2 Inc. and its suppliers, if any.
 ~ Dissemination of any information or reproduction of any material contained
 ~ herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
 ~ You may not alter or remove any copyright or other notice from copies of this content."
 ~
--%>

<%@ page import="org.owasp.encoder.Encode" %>
<%@ page import="org.wso2.carbon.identity.application.authentication.endpoint.util.Constants" %>
<%@ page import="java.io.File" %>
<%@ page import="java.util.Map" %>
<%@ page import="org.wso2.carbon.identity.application.authenticator.totp.util.TOTPUtil" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ include file="includes/localize.jsp" %>
<jsp:directive.include file="includes/init-url.jsp"/>

<%
    request.getSession().invalidate();
    String queryString = request.getQueryString();
    Map<String, String> idpAuthenticatorMapping = null;
    if (request.getAttribute(Constants.IDP_AUTHENTICATOR_MAP) != null) {
        idpAuthenticatorMapping = (Map<String, String>) request.getAttribute(Constants.IDP_AUTHENTICATOR_MAP);
    }

    boolean isSendVerificationCodeByEmailEnabled = TOTPUtil.isSendVerificationCodeByEmailEnabled();

    String errorMessage = AuthenticationEndpointUtil.i18n(resourceBundle,"error.retry");
    String authenticationFailed = "false";

    if (Boolean.parseBoolean(request.getParameter(Constants.AUTH_FAILURE))) {
        authenticationFailed = "true";

        if (request.getParameter(Constants.AUTH_FAILURE_MSG) != null) {
            errorMessage = Encode.forHtmlAttribute(request.getParameter(Constants.AUTH_FAILURE_MSG));

             if (errorMessage.equalsIgnoreCase("authentication.fail.message") ||
                     errorMessage.equalsIgnoreCase("login.fail.message")) {
                errorMessage = AuthenticationEndpointUtil.i18n(resourceBundle,"error.retry");
            }
        }
    }
%>
<html>
    <head>
        <!-- header -->
        <%
            File headerFile = new File(getServletContext().getRealPath("extensions/header.jsp"));
            if (headerFile.exists()) {
        %>
        <jsp:include page="extensions/header.jsp"/>
        <% } else { %>
        <jsp:include page="includes/header.jsp"/>
        <% } %>

        <script src="js/scripts.js"></script>
        <script src="/totpauthenticationendpoint/js/scripts.js"></script>
        <!--[if lt IE 9]>
        <script src="js/html5shiv.min.js"></script>
        <script src="js/respond.min.js"></script>
        <![endif]-->

        <script>
            // Handle form submission preventing double submission.
            $(document).ready(function(){
                $.fn.preventDoubleSubmission = function() {
                    $(this).on('submit',function(e){
                        var $form = $(this);
                        if ($form.data('submitted') === true) {
                            // Previously submitted - don't submit again.
                            e.preventDefault();
                            console.warn("Prevented a possible double submit event");
                        } else {
                            // Mark it so that the next submit can be ignored.
                            $form.data('submitted', true);
                        }
                    });

                    return this;
                };
                $('#totpForm').preventDoubleSubmission();
            });
        </script>
        <script type="text/javascript">
            var emailLinkClicked = false;

            function generateInstruction() {
                var isEmailCodeEnabled = "<%= isSendVerificationCodeByEmailEnabled %>" === "true" ? true : false;
                var authAppCodeText = '<%=AuthenticationEndpointUtil.i18n(resourceBundle, "enter.verification.code.got.by.device")%>';
                var emailCodeText = '<%=AuthenticationEndpointUtil.i18n(resourceBundle, "enter.verification.code.got.via.email")%>';

                var text = isEmailCodeEnabled && emailLinkClicked ? emailCodeText : authAppCodeText;
                $("#instruction").empty().append(text);
            }

            $(document).ready(function() {
                generateInstruction();
            })
        </script>
    </head>

    <body class="login-portal layout totp-portal-layout">
        <div class="page-wrapper">
            <main class="center-segment">
                <%
                    if (StringUtils.equals(tenantForTheming, IdentityManagementEndpointConstants.SUPER_TENANT)) {
                %>
                    <div class="slogan-container">
                        <div class="theme-icon inline auto transparent product-logo portal-logo">
                            <img src="libs/themes/asgardio/assets/images/logo-full-light.svg" alt="product-logo" />
                        </div>
                
                        <h2 class="ui header portal-logo-tagline">
                            Freedom through security for everyone
                            <span>
                                Secure | Simple | Stackable
                            </span>
                        </h2>
                    </div>
                <%
                    }
                %>
                <div class="ui container medium center aligned middle aligned">
                    <!-- product-title -->
                    <%
                        File productTitleFile = new File(getServletContext().getRealPath("extensions/product-title.jsp"));
                        if (productTitleFile.exists()) {
                    %>
                        <%
                            if (StringUtils.equals(tenantForTheming, IdentityManagementEndpointConstants.SUPER_TENANT)) {
                        %>
                            <div class="product-title">
                                <jsp:include page="extensions/product-title.jsp"/>
                            </div>
                        <% } else { %>
                            <jsp:include page="extensions/product-title.jsp"/>
                        <% } %>
                    <% } else { %>
                        <jsp:include page="includes/product-title.jsp"/>
                    <% } %>

                    <div class="ui segment">
                        <!-- page content -->
                        <h3 class="ui header text-center">
                            Verify your identity
                        </h3>

                        <%
                            if ("true".equals(authenticationFailed)) {
                        %>
                                <div class="ui negative message" id="failed-msg"><%=errorMessage%></div>
                                <div class="ui divider hidden"></div>
                        <% } %>

                        <input id="username" type="hidden"
                               value='<%=Encode.forHtmlAttribute(request.getParameter("username"))%>'>

                        <div class="segment-form">
                            <form action="../commonauth" method="post" id="totpForm" class="ui large form">
                                <p class="text-center" id="instruction"></p>
                                <div class="field">
                                    <input hidden type="text"  id="token" name="token" class="form-control" placeholder="<%=AuthenticationEndpointUtil.i18n(resourceBundle, "verification.code")%>">
                                </div>

                                <div class="equal width fields">
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-1" name="pincode-1" 
                                               onkeyup="movetoNext(this, 'pincode-2', null)" 
                                               tabindex="1" placeholder="·" autofocus maxlength="1">
                                    </div>
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-2" name="pincode-2"  
                                               onkeyup="movetoNext(this, 'pincode-3', 'pincode-1')" 
                                               tabindex="2" placeholder="·" maxlength="1">
                                    </div>
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-3" name="pincode-3" 
                                               onkeyup="movetoNext(this, 'pincode-4', 'pincode-2')" 
                                               tabindex="3" placeholder="·" maxlength="1">
                                    </div>
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-4" name="pincode-4" tabindex="4" 
                                               onkeyup="movetoNext(this, 'pincode-5', 'pincode-3')" 
                                               placeholder="·" maxlength="1">
                                    </div>
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-5" name="pincode-5" tabindex="5" 
                                               onkeyup="movetoNext(this, 'pincode-6', 'pincode-4')" 
                                               placeholder="·" maxlength="1">
                                    </div>
                                    <div class="field mt-5">
                                        <input class="text-center" id="pincode-6" name="pincode-6" tabindex="6" 
                                               onkeyup="movetoNext(this, null, 'pincode-5')" 
                                               placeholder="·" maxlength="1">
                                    </div>  
                                </div>

                                <input id="sessionDataKey" type="hidden" name="sessionDataKey"
                                       value='<%=Encode.forHtmlAttribute(request.getParameter("sessionDataKey"))%>' />
                                <div class="ui divider hidden"></div>
                                <div>
                                    <input type="button" id="subButton" onclick="sub(); return false;"
                                    value="<%=AuthenticationEndpointUtil.i18n(resourceBundle, "authenticate")%>" 
                                    class="ui primary fluid large button" />
                                </div>

                                <div class="text-center mt-1">
                                    <% if(isSendVerificationCodeByEmailEnabled) { %>
                                        <a class="ui button link-button" id="genToken" href="#"
                                        onclick="return requestTOTPToken();">
                                        <%=AuthenticationEndpointUtil.i18n(resourceBundle, "get.verification.code")%>
                                        </a>
                                    <% } else {
                                        String multiOptionURI = request.getParameter("multiOptionURI");
                                        if (multiOptionURI != null) {
                                    %>
                                        <a class="ui large button link-button" id="goBackLink"
                                            href='<%=Encode.forHtmlAttribute(multiOptionURI)%>'>
                                                <%=AuthenticationEndpointUtil.i18n(resourceBundle, "choose.other.option")%>
                                        </a>
                                    <% } } %>
                                </div>
                                
                            </div>
                            </form>
                        </div>
                </div>
            </main>

            <!-- product-footer -->
            <%
                File productFooterFile = new File(getServletContext().getRealPath("extensions/product-footer.jsp"));
                if (productFooterFile.exists()) {
            %>
            <jsp:include page="extensions/product-footer.jsp"/>
            <% } else { %>
            <jsp:include page="includes/product-footer.jsp"/>
            <% } %>
        </div>

        <!-- footer -->
        <%
            File footerFile = new File(getServletContext().getRealPath("extensions/footer.jsp"));
            if (footerFile.exists()) {
        %>
        <jsp:include page="extensions/footer.jsp"/>
        <% } else { %>
        <jsp:include page="includes/footer.jsp"/>
        <% } %>

        <script type="text/javascript">

            function movetoNext(current, nextFieldID, previousID) {
                var key = event.keyCode || event.charCode;
                if (nextFieldID != null && current.value.length >= current.maxLength) {
                    document.getElementById(nextFieldID).focus();
                }
                if( key == 8 || key == 46 ) {
                    if ( previousID != null) {
                        document.getElementById(previousID).focus();
                    }
                }
            }

            function sub() {
                var pin1 = document.getElementById("pincode-1").value;
                var pin2 = document.getElementById("pincode-2").value;
                var pin3 = document.getElementById("pincode-3").value;
                var pin4 = document.getElementById("pincode-4").value;
                var pin5 = document.getElementById("pincode-5").value;
                var pin6 = document.getElementById("pincode-6").value;
                
                var token = pin1 + pin2 + pin3 + pin4 + pin5 + pin6;
            
                document.getElementById('token').value = token;

                if ( pin1 !=null &  pin2 !=null & pin3 !=null & pin5 !=null & pin6 !=null) {
                    document.getElementById("totpForm").submit();
                }

            }
            
            $('#subButton').attr('disabled', true);
            $('#pincode-6').on('keyup', function() {
                if ($('#pincode-1').val() != '' && $('#pincode-2').val() != '' 
                && $('#pincode-3').val() != '' && $('#pincode-4').val() != '' && $('#pincode-5').val() != ''  && $('#pincode-6').val() != '') {
                    $('#subButton').attr('disabled', false);
                } else {
                    $('#subButton').attr('disabled', true);
                }
            });
        </script>
    </body>
    
</html>
