<#--
MIT License

Copyright (c) 2020 GitHub user u/garronej

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.
-->
<#function are_same_path path searchedPath>
  <#if path?size != searchedPath?size>
    <#return false>
  </#if>
  <#local i=0>
  <#list path as property>
    <#local searchedProperty=searchedPath[i]>
    <#if searchedProperty?is_string && searchedProperty == "*">
      <#continue>
    </#if>
    <#if searchedProperty?is_string && !property?is_string>
      <#return false>
    </#if>
    <#if searchedProperty?is_number && !property?is_number>
      <#return false>
    </#if>
    <#if searchedProperty?string != property?string>
      <#return false>
    </#if>
    <#local i+= 1>
  </#list>
  <#return true>
</#function>
<#function ftl_object_to_js_code_declaring_an_object pageId object path>
  <#local isHash = "">
  <#attempt>
    <#local isHash = object?is_hash || object?is_hash_ex>
  <#recover>
    <#return "ABORT: Can't evaluate if " + path?join(".") + " is hash">
  </#attempt>

  <#if isHash>

    <#if path?size gt 10>
      <#return "ABORT: Too many recursive calls">
    </#if>

    <#local keys = "">

    <#attempt>
      <#local keys = object?keys>
    <#recover>
      <#return "ABORT: We can't list keys on this object">
    </#attempt>

    <#local out_seq = []>
    <#list keys as key>
      <#if ["class","declaredConstructors","superclass","declaringClass" ]?seq_contains(key) >
        <#continue>
      </#if>

      <#if 
        (
          ["loginUpdatePasswordUrl", "loginUpdateProfileUrl", "loginUsernameReminderUrl", "loginUpdateTotpUrl"]?seq_contains(key) && 
          are_same_path(path, ["url"])
        ) || (
          key == "updateProfileCtx" && 
          are_same_path(path, [])
        ) || (
          key == "loginAction" && 
          are_same_path(path, ["url"]) && 
          ["saml-post-form.ftl", "error.ftl", "info.ftl"]?seq_contains(pageId) &&
          !(auth?has_content && auth.showTryAnotherWayLink())
        ) || (
          ["contextData", "idpConfig", "idp", "authenticationSession"]?seq_contains(key) &&
          are_same_path(path, ["brokerContext"]) &&
          ["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(pageId)
        ) || (
          key == "identityProviderBrokerCtx" && 
          are_same_path(path, []) &&
          ["login-idp-link-confirm.ftl", "login-idp-link-email.ftl" ]?seq_contains(pageId)
        ) || (
          ["masterAdminClient", "delegateForUpdate", "defaultRole"]?seq_contains(key) &&
          are_same_path(path, ["realm"])
        ) || (
          ["password"]?seq_contains(key) &&
          are_same_path(path, ["login"])
        )
      >
        <#continue>
      </#if>

      <#if key == "attemptedUsername" && are_same_path(path, ["auth"])>
        <#attempt>
          <#if !(auth?has_content && auth.showUsername() && !auth.showResetCredentials())>
            <#continue>
          </#if>
        <#recover>
        </#attempt>
      </#if>
                
      <#attempt>
        <#if !object[key]??>
          <#continue>
        </#if>
      <#recover>
        <#local out_seq += ["/*Couldn't test if '" + key + "' is available on this object*/"]>
        <#continue>
      </#attempt>

      <#local propertyValue = "">
      <#attempt>
        <#local propertyValue = object[key]>
      <#recover>
        <#local out_seq += ["/*Couldn't dereference '" + key + "' on this object*/"]>
        <#continue>
      </#attempt>

      <#local rec_out = ftl_object_to_js_code_declaring_an_object(pageId, propertyValue, path + [ key ])>
      <#if rec_out?starts_with("ABORT:")>
        <#local errorMessage = rec_out?remove_beginning("ABORT:")>
        <#if errorMessage != " It's a method" >
          <#local out_seq += ["/*" + key + ": " + errorMessage + "*/"]>
        </#if>
        <#continue>
      </#if>

      <#local out_seq +=  ['"' + key + '": ' + rec_out + ","]>
    </#list>

    <#return (["{"] + out_seq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "}"])?join("\n")>

  </#if>

  <#local isMethod = "">
  <#attempt>
    <#local isMethod = object?is_method>
  <#recover>
    <#return "ABORT: Can't test if it'sa method.">
  </#attempt>

  <#if isMethod>
    <#if are_same_path(path, ["auth", "showUsername"])>
      <#attempt>
        <#return auth.showUsername()?c>
      <#recover>
        <#return "ABORT: Couldn't evaluate auth.showUsername()">
      </#attempt>
    </#if>

    <#if are_same_path(path, ["auth", "showResetCredentials"])>
      <#attempt>
        <#return auth.showResetCredentials()?c>
      <#recover>
        <#return "ABORT: Couldn't evaluate auth.showResetCredentials()">
      </#attempt>
    </#if>

    <#if are_same_path(path, ["auth", "showTryAnotherWayLink"])>
      <#attempt>
        <#return auth.showTryAnotherWayLink()?c>
      <#recover>
        <#return "ABORT: Couldn't evaluate auth.showTryAnotherWayLink()">
      </#attempt>
    </#if>

    <#return "ABORT: It's a method">
  </#if>

  <#local isBoolean = "">
  <#attempt>
    <#local isBoolean = object?is_boolean>
  <#recover>
    <#return "ABORT: Can't test if it's a boolean">
  </#attempt>

  <#if isBoolean>
    <#return object?c>
  </#if>

  <#local isEnumerable = "">
  <#attempt>
    <#local isEnumerable = object?is_enumerable>
  <#recover>
    <#return "ABORT: Can't test if it's an enumerable">
  </#attempt>

  <#if isEnumerable>
    <#local out_seq = []>
    <#local i = 0>

    <#list object as array_item>
      <#if !array_item??>
        <#local out_seq += ["null,"]>
        <#continue>
      </#if>

      <#local rec_out = ftl_object_to_js_code_declaring_an_object(pageId, array_item, path + [ i ])>
      <#local i = i + 1>

      <#if rec_out?starts_with("ABORT:")>
        <#local errorMessage = rec_out?remove_beginning("ABORT:")>
        <#if errorMessage != " It's a method" >
          <#local out_seq += ["/*" + i?string + ": " + errorMessage + "*/"]>
        </#if>

        <#continue>
      </#if>
      <#local out_seq += [rec_out + ","]>
    </#list>

    <#return (["["] + out_seq?map(str -> ""?right_pad(4 * (path?size + 1)) + str) + [ ""?right_pad(4 * path?size) + "]"])?join("\n")>
  </#if>

  <#attempt>
    <#return '"' + object?js_string + '"'>;
  <#recover>
  </#attempt>

  <#return "ABORT: Couldn't convert into string non hash, non method, non boolean, non enumerable object">
</#function>

<#macro baseLayout pageId="template.ftl">
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <link rel="icon" href="${url.resourcesPath}/img/favicon.ico">
    <title>${msg("loginTitle",(realm.displayName!''))}</title>
    <style>
      body {
        background-image: url("${url.resourcesPath}/img/background.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
      }
    </style>
    <script>
      window.kcContext = ${ftl_object_to_js_code_declaring_an_object(pageId, .data_model, [])?no_esc}
    </script>
    <#nested "head">
</head>
<body>
    <div id="app"></div>
    <#nested "scripts">
</body>
</html>
</#macro>