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

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.timezone.TimeZoneService;
import com.atlassian.soy.renderer.SoyTemplateRenderer;
import com.atlassian.stash.internal.locale.InternalLocaleService;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.ZoneId;
import java.util.Optional;

/**
 * Simple UI for setting the server's timezone.
 *
 * @since 4.6
 */
public class ServerTimeZoneFormFragment extends AbstractTimeZoneFormFragment {

    private final I18nService i18nService;
    private final InternalLocaleService localeService;
    private final TimeZoneService timeZoneService;

    ServerTimeZoneFormFragment(@Nonnull I18nService i18nService,
                               @Nonnull InternalLocaleService localeService,
                               @Nonnull SoyTemplateRenderer soyTemplateRenderer,
                               @Nonnull TimeZoneService timeZoneService) {
        super(i18nService, localeService, soyTemplateRenderer);
        this.i18nService = i18nService;
        this.localeService = localeService;
        this.timeZoneService = timeZoneService;
    }

    @Override
    void execute(@Nullable ZoneId zoneId) {
        timeZoneService.setServerTimeZone(zoneId);
    }

    @Nonnull
    @Override
    Optional<ZoneId> getCurrent() {
        return timeZoneService.getServerTimeZone();
    }

    @Nonnull
    @Override
    LocalizedZoneCollection.LocalizedTimeZone getDefaultTimeZone() {
        return LocalizedZoneCollection.timeZone(timeZoneService.getJvmTimeZone(), localeService.getLocale(),
                i18nService.getMessage("bitbucket.web.timezone.default.time.zone"), "");
    }

    @Nonnull
    @Override
    String getDescription() {
        return i18nService.getMessage("bitbucket.web.timezone.description");
    }

    @Override
    boolean isLongField() {
        return true;
    }
}
