<!--
~ 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."
-->

<!-- Tenant resolve JSP must be included in the calling script inorder to resolve tenant context -->

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="org.json.JSONObject" %>
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="org.wso2.carbon.identity.mgt.endpoint.util.client.BrandingPreferenceRetrievalClient" %>
<%@ page import="org.wso2.carbon.identity.mgt.endpoint.util.client.BrandingPreferenceRetrievalClientException" %>
<%@ page import="org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointConstants" %>

<%
    JSONObject brandingPreference = null;

    boolean isBrandingEnabledInTenantPreferences = true;
    boolean isSelfSignUpEnabledInTenantPreferences = true;
    boolean isPasswordRecoveryEnabledInTenantPreferences = true;
    // This should be decided based on the subscription tier.
    // TODO: Properly resolve once subscription API is integrated in to the console.
    // Tracked Here: https://github.com/wso2-enterprise/asgardeo-product/issues/8625
    boolean shouldRemoveDefaultBranding = true;
    @Deprecated
    JSONObject colors = null;
    JSONObject theme = null;
    String activeThemeName = "";
    String overrideStylesheet = "";
    String copyrightText = "";
    String siteTitle = "Asgardeo by WSO2";
    String supportEmail = "asgardeo-help@wso2.com";
    String logoURL = "";
    String logoAlt = "";
    String faviconURL = "";
    String privacyPolicyURL = "";
    String termsOfUseURL = "";
    String cookiePolicyURL = "";
    String selfSignUpOverrideURL = "";
    String passwordRecoveryOverrideURL = "";
    String layout = "default";
    String layoutFileRelativePath = "includes/layouts/default/body.ser";
    Map<String, Object> layoutData = new HashMap<String, Object>();

    try {
        String DEFAULT_RESOURCE_LOCALE = "en-US";
        String ORG_PREFERENCE_RESOURCE_TYPE = "ORG";
        String APP_PREFERENCE_RESOURCE_TYPE = "APP";

        String tenantRequestingPreferences = tenantForTheming;
        String applicationRequestingPreferences = spAppName;
        String preferenceResourceType = ORG_PREFERENCE_RESOURCE_TYPE;

        // If the `sp` param is defined, set the resource type as app.
        if (StringUtils.isNotBlank(applicationRequestingPreferences)) {
            preferenceResourceType = APP_PREFERENCE_RESOURCE_TYPE;
        }

        // Only engage the preference retrieval if the flow is not super tenant.
        if (!StringUtils.equals(tenantRequestingPreferences, IdentityManagementEndpointConstants.SUPER_TENANT)) {

            BrandingPreferenceRetrievalClient brandingPreferenceRetrievalClient = new BrandingPreferenceRetrievalClient();
            JSONObject brandingPreferenceResponse = brandingPreferenceRetrievalClient.getPreference(tenantRequestingPreferences,
                    preferenceResourceType, applicationRequestingPreferences, DEFAULT_RESOURCE_LOCALE);

            // Preferences response object pointer keys.
            String PREFERENCE_KEY = "preference";
            String ACTIVE_THEME_KEY = "activeTheme";
            String COLORS_KEY = "colors";
            String THEME_KEY = "theme";
            String STYLESHEETS_KEY = "stylesheets";
            String ACCOUNT_APP_STYLESHEET_KEY = "accountApp";
            String ORG_DETAILS_KEY = "organizationDetails";
            String COPYRIGHT_TEXT_KEY = "copyrightText";
            String SITE_TITLE_KEY = "siteTitle";
            String SUPPORT_EMAIL_KEY = "supportEmail";
            String IMAGES_KEY = "images";
            String IMAGE_URL_KEY = "imgURL";
            String ALT_TEXT_KEY = "altText";
            String LOGO_KEY = "logo";
            String FAVICON_KEY = "favicon";
            String URLS_KEY = "urls";
            String PRIVACY_POLICY_URL_KEY = "privacyPolicyURL";
            String TERMS_OF_USE_URL_KEY = "termsOfUseURL";
            String COOKIE_POLICY_URL_KEY = "cookiePolicyURL";
            String SELF_SIGN_UP_URL_KEY = "selfSignUpURL";
            String PASSWORD_RECOVERY_URL_KEY = "passwordRecoveryURL";
            String CONFIGS_KEY = "configs";
            String IS_BRANDING_ENABLED_KEY= "isBrandingEnabled";
            String IS_SELF_SIGN_UP_ENABLED_KEY = "isSelfSignUpEnabled";
            String IS_PASSWORD_RECOVERY_ENABLED_KEY = "isPasswordRecoveryEnabled";
            String SHOULD_REMOVE_DEFAULT_BRANDING_KEY = "removeAsgardeoBranding";

            if (brandingPreferenceResponse.has(PREFERENCE_KEY)) {
                brandingPreference = brandingPreferenceResponse.getJSONObject(PREFERENCE_KEY);
            }

%>

            <%@include file="layout-resolver.jsp" %>

<%

            // Proceed only if `preferences` object is defined.
            if (brandingPreference != null) {
                // First, check if Branding is enabled.
                if (brandingPreference.has(CONFIGS_KEY)) {
                    if (brandingPreference.getJSONObject(CONFIGS_KEY).has(IS_BRANDING_ENABLED_KEY)) {
                        isBrandingEnabledInTenantPreferences = brandingPreference.getJSONObject(CONFIGS_KEY).getBoolean(IS_BRANDING_ENABLED_KEY);
                    }
                }

                // Proceed only if the branding is enabled.
                if (isBrandingEnabledInTenantPreferences) {
                    // Configs
                    if (brandingPreference.has(CONFIGS_KEY)) {
                        if (brandingPreference.getJSONObject(CONFIGS_KEY).has(IS_SELF_SIGN_UP_ENABLED_KEY)) {
                            isSelfSignUpEnabledInTenantPreferences = brandingPreference.getJSONObject(CONFIGS_KEY).getBoolean(IS_SELF_SIGN_UP_ENABLED_KEY);
                        }

                        if (brandingPreference.getJSONObject(CONFIGS_KEY).has(IS_PASSWORD_RECOVERY_ENABLED_KEY)) {
                            isPasswordRecoveryEnabledInTenantPreferences = brandingPreference.getJSONObject(CONFIGS_KEY).getBoolean(IS_PASSWORD_RECOVERY_ENABLED_KEY);
                        }

                        if (brandingPreference.getJSONObject(CONFIGS_KEY).has(SHOULD_REMOVE_DEFAULT_BRANDING_KEY)) {
                            shouldRemoveDefaultBranding = brandingPreference.getJSONObject(CONFIGS_KEY).getBoolean(SHOULD_REMOVE_DEFAULT_BRANDING_KEY);
                        }
                    }

                    // Colors.
                    // @deprecated Moved in to `theme` object. Kept here for backward compatibility.
                    if (brandingPreference.has(COLORS_KEY)) {
                        colors = brandingPreference.getJSONObject(COLORS_KEY);
                    }

                    // Theme
                    if (brandingPreference.has(THEME_KEY)) {
                        if (brandingPreference.getJSONObject(THEME_KEY).has(ACTIVE_THEME_KEY)) {
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(THEME_KEY).getString(ACTIVE_THEME_KEY))) {
                                activeThemeName = brandingPreference.getJSONObject(THEME_KEY).getString(ACTIVE_THEME_KEY);

                                if (brandingPreference.getJSONObject(THEME_KEY).has(activeThemeName)
                                    && brandingPreference.getJSONObject(THEME_KEY).getJSONObject(activeThemeName) != null) {

                                    theme = brandingPreference.getJSONObject(THEME_KEY).getJSONObject(activeThemeName);

                                    if (theme.has(IMAGES_KEY) && theme.getJSONObject(IMAGES_KEY) != null) {
                                        if (theme.getJSONObject(IMAGES_KEY).has(LOGO_KEY) && theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY) != null) {
                                            if (theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).has(IMAGE_URL_KEY)
                                                && !StringUtils.isBlank(theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(IMAGE_URL_KEY))) {

                                                logoURL = theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(IMAGE_URL_KEY);
                                            }
                                            if (theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).has(ALT_TEXT_KEY)
                                                && !StringUtils.isBlank(theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(ALT_TEXT_KEY))) {

                                                logoAlt = theme.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(ALT_TEXT_KEY);
                                            }
                                        }
                                        if (theme.getJSONObject(IMAGES_KEY).has(FAVICON_KEY) && theme.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY) != null) {
                                            if (theme.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).has(IMAGE_URL_KEY)
                                                && !StringUtils.isBlank(theme.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).getString(IMAGE_URL_KEY))) {

                                                faviconURL = theme.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).getString(IMAGE_URL_KEY);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Stylesheets
                    if (brandingPreference.has(STYLESHEETS_KEY)) {
                        if (brandingPreference.getJSONObject(STYLESHEETS_KEY).has(ACCOUNT_APP_STYLESHEET_KEY)) {
                            // Only assign the `stylesheet` from response if not empty.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(STYLESHEETS_KEY).getString(ACCOUNT_APP_STYLESHEET_KEY))) {
                                overrideStylesheet = brandingPreference.getJSONObject(STYLESHEETS_KEY).getString(ACCOUNT_APP_STYLESHEET_KEY);
                            }
                        }
                    }

                    // Organization Details
                    if (brandingPreference.has(ORG_DETAILS_KEY)) {
                        if (brandingPreference.getJSONObject(ORG_DETAILS_KEY).has(COPYRIGHT_TEXT_KEY)) {
                            // Only assign the `copyright` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(COPYRIGHT_TEXT_KEY))) {
                                copyrightText = brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(COPYRIGHT_TEXT_KEY);
                            }
                        }

                        if (brandingPreference.getJSONObject(ORG_DETAILS_KEY).has(SITE_TITLE_KEY)) {
                            // Only assign the `siteTitle` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(SITE_TITLE_KEY))) {
                                siteTitle = brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(SITE_TITLE_KEY);
                            }
                        }

                        if (brandingPreference.getJSONObject(ORG_DETAILS_KEY).has(SUPPORT_EMAIL_KEY)) {
                            // Only assign the `supportEmail` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(SUPPORT_EMAIL_KEY))) {
                                supportEmail = brandingPreference.getJSONObject(ORG_DETAILS_KEY).getString(SUPPORT_EMAIL_KEY);
                            }
                        }
                    }

                    // Images
                    if (brandingPreference.has(IMAGES_KEY)) {
                        if (brandingPreference.getJSONObject(IMAGES_KEY).has(LOGO_KEY)) {
                            if (brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).has(IMAGE_URL_KEY)) {
                                // Only assign the `logoURL` from response if not empty. Else use the default value.
                                if (!StringUtils.isBlank(brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(IMAGE_URL_KEY))) {
                                    logoURL = brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(IMAGE_URL_KEY);
                                }
                            }

                            if (brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).has(ALT_TEXT_KEY)) {
                                // Only assign the `logoAlt` from response if not empty. Else use the default value.
                                if (!StringUtils.isBlank(brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(ALT_TEXT_KEY))) {
                                    logoAlt = brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(LOGO_KEY).getString(ALT_TEXT_KEY);
                                }
                            }
                        }

                        if (brandingPreference.getJSONObject(IMAGES_KEY).has(FAVICON_KEY)) {
                            if (brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).has(IMAGE_URL_KEY)) {
                                // Only assign the `faviconURL` from response if not empty. Else use the default value.
                                if (!StringUtils.isBlank(brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).getString(IMAGE_URL_KEY))) {
                                    faviconURL = brandingPreference.getJSONObject(IMAGES_KEY).getJSONObject(FAVICON_KEY).getString(IMAGE_URL_KEY);
                                }
                            }
                        }
                    }

                    // Links
                    if (brandingPreference.has(URLS_KEY)) {
                        if (brandingPreference.getJSONObject(URLS_KEY).has(PRIVACY_POLICY_URL_KEY)) {
                            // Only assign the `privacyPolicyURL` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(URLS_KEY).getString(PRIVACY_POLICY_URL_KEY))) {
                                privacyPolicyURL = brandingPreference.getJSONObject(URLS_KEY).getString(PRIVACY_POLICY_URL_KEY);
                            }
                        }

                        if (brandingPreference.getJSONObject(URLS_KEY).has(TERMS_OF_USE_URL_KEY)) {
                            // Only assign the `termsOfUseURL` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(URLS_KEY).getString(TERMS_OF_USE_URL_KEY))) {
                                termsOfUseURL = brandingPreference.getJSONObject(URLS_KEY).getString(TERMS_OF_USE_URL_KEY);
                            }
                        }

                        if (brandingPreference.getJSONObject(URLS_KEY).has(COOKIE_POLICY_URL_KEY)) {
                            // Only assign the `cookiePolicyURL` from response if not empty. Else use the default value.
                            if (!StringUtils.isBlank(brandingPreference.getJSONObject(URLS_KEY).getString(COOKIE_POLICY_URL_KEY))) {
                                cookiePolicyURL = brandingPreference.getJSONObject(URLS_KEY).getString(COOKIE_POLICY_URL_KEY);
                            }
                        }

                        if (brandingPreference.getJSONObject(URLS_KEY).has(SELF_SIGN_UP_URL_KEY)) {
                            selfSignUpOverrideURL = brandingPreference.getJSONObject(URLS_KEY).getString(SELF_SIGN_UP_URL_KEY);
                        }

                        if (brandingPreference.getJSONObject(URLS_KEY).has(PASSWORD_RECOVERY_URL_KEY)) {
                            passwordRecoveryOverrideURL = brandingPreference.getJSONObject(URLS_KEY).getString(PASSWORD_RECOVERY_URL_KEY);
                        }
                    }

                }
            }
        }

    } catch (BrandingPreferenceRetrievalClientException e) {
        // Exception is ignored and the variable will use the fallbacks.
        // TODO: Move the duplicated logic to a common place.
    } finally {

        // Set fallbacks.
        if (StringUtils.isEmpty(logoURL)) {
            if (StringUtils.isEmpty(activeThemeName)) {
                logoURL = "libs/themes/asgardio/assets/images/branding/asgardeo-logo.svg";
            } else if (StringUtils.equalsIgnoreCase(activeThemeName, "DARK")) {
                logoURL = "libs/themes/asgardio/assets/images/branding/asgardeo-logo-white.svg";
            } else {
                logoURL = "libs/themes/asgardio/assets/images/branding/asgardeo-logo.svg";
            }
        }

        if (StringUtils.isEmpty(logoAlt)) {
            if (StringUtils.isEmpty(activeThemeName)) {
                logoAlt = "Asgardeo Logo";
            } else if (StringUtils.equalsIgnoreCase(activeThemeName, "DARK")) {
                logoAlt = "Asgardeo Logo White Variation";
            } else {
                logoAlt = "Asgardeo Logo";
            }
        }

        if (StringUtils.isEmpty(faviconURL)) {
            faviconURL = "libs/themes/asgardio/assets/images/branding/favicon.ico";
        }
    }
%>
