package com.atlassian.stash.internal.locale;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.stash.internal.user.InternalNormalUser;
import com.google.common.annotations.VisibleForTesting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.Locale;
import java.util.function.Supplier;

@Component("localeService")
public class DefaultLocaleService implements InternalLocaleService {

    private final AuthenticationContext authenticationContext;
    private final Supplier<Locale> defaultLocale;

    @Autowired
    public DefaultLocaleService(AuthenticationContext authenticationContext) {
        this(authenticationContext, LocaleContextHolder::getLocale);
    }

    @VisibleForTesting
    DefaultLocaleService(AuthenticationContext authenticationContext, Supplier<Locale> defaultLocale) {
        this.authenticationContext = authenticationContext;
        this.defaultLocale = defaultLocale;
    }

    @Nonnull
    @Override
    public Locale getLocale() {
        return InternalNormalUser.fromUser(authenticationContext.getCurrentUser())
                .map(InternalNormalUser::getLocale)
                .orElseGet(this::getDefaultLocale);
    }

    private Locale getDefaultLocale() {
        Locale locale = defaultLocale.get();
        if (locale == null) {
            throw new IllegalStateException("No default locale available.");
        }
        return locale;
    }
}
