package com.atlassian.stash.internal.web.locale;

import com.atlassian.fugue.Pair;
import com.atlassian.soy.renderer.SoyTemplateRenderer;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.stash.internal.language.InternalLanguageService;
import com.atlassian.stash.internal.user.InternalLocaleManager;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.bitbucket.auth.AuthenticationContext;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.atlassian.fugue.Pair.pair;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.util.Collections.singletonList;

public class UserLocaleFormFragment extends AbstractLocaleFormFragment {

    private final AuthenticationContext authenticationContext;
    private final I18nService i18nService;
    private final InternalLocaleManager localeManager;

    public UserLocaleFormFragment(I18nService i18nService, InternalLanguageService languageService,
                                  SoyTemplateRenderer soyTemplateRenderer, AuthenticationContext authenticationContext,
                                  InternalLocaleManager localeManager) {
        super(languageService, soyTemplateRenderer);
        this.i18nService = i18nService;
        this.authenticationContext = authenticationContext;
        this.localeManager = localeManager;
    }

    @Override
    protected Pair<Locale, List<Map<String, Object>>> load(Map<String, Object> context) {
        return pair(
                firstNonNull(localeManager.getLocale(getUser(context)), Locale.ROOT),
                // This value needs to be space - blank breaks on select2
                singletonList(UserLocaleWebUtils.asData(" ", i18nService.getMessage("bitbucket.web.user.account.settings.locale.default")))
        );
    }

    @Override
    protected void save(Map<String, Object> context, Locale locale) {
        localeManager.setLocale(getUser(context), locale);
    }

    private ApplicationUser getUser(Map<String, Object> context) {
        // This is a nasty transgression, but otherwise when you 'save' it doesn't keep the previous value (for _this_ page)
        // The alternative is to pass the request parameters through the context
        return authenticationContext.getCurrentUser();
    }
}
