package com.atlassian.stash.internal.johnson;

import com.atlassian.johnson.JohnsonEventContainer;
import com.atlassian.johnson.event.ApplicationEventCheck;
import com.atlassian.johnson.event.Event;
import com.atlassian.johnson.event.EventLevel;
import com.atlassian.johnson.event.EventType;
import com.atlassian.bitbucket.Product;
import com.google.common.collect.ImmutableSet;

import javax.annotation.Nonnull;
import javax.servlet.ServletContext;
import java.util.Locale;
import java.util.Set;

/**
 * Prevents Stash from starting when the default locale is known to
 * cause system failures.
 *
 * @since 2.9.5
 */
public class LocaleApplicationEventCheck extends AbstractHelpPathProvider implements ApplicationEventCheck {

    private static final String TURKISH_ISO_CODE = "tur";

    /**
     * Set of locales that causes system failures later on:
     * <p>
     * <ul>
     * <li><em>Turkish</em>: failure in Hibernate (HHH-8765), see https://jira.atlassian.com/browse/STASH-3828.</li>
     * </ul>
     * <p>
     * Note that the locales are defined using their {@link Locale#getISO3Language() ISO language code}.
     */
    private static final Set<String> UNSUPPORTED_LOCALES = ImmutableSet.of(TURKISH_ISO_CODE);

    @Override
    public void check(@Nonnull JohnsonEventContainer eventContainer, @Nonnull ServletContext context) {
        Locale locale = Locale.getDefault();
        check(eventContainer, locale);
    }

    protected void check(JohnsonEventContainer eventContainer, Locale locale) {
        if (UNSUPPORTED_LOCALES.contains(locale.getISO3Language())) {
            eventContainer.addEvent(createEvent(locale));
        }
    }

    private Event createEvent(Locale locale) {
        HelpDetails help = getHelp("bitbucket.kb.db.failure.with.turkish.locale", "knowledge base article", "https://confluence.atlassian.com/x/uIKZGQ");
        String description = String.format("The current locale (%2$s) is not supported by %1$s.%n" +
                "Please follow the instructions in this <a href=\"%3$s\">knowledge base article</a> to resolve the issue.",
                Product.NAME, locale.getDisplayName(), help.getUrl());

        return new Event(EventType.get("unsupported-locale"),
                description, EventLevel.get(EventLevel.FATAL));
    }

}
