package com.atlassian.stash.internal.sal;

import com.atlassian.bitbucket.timezone.TimeZoneService;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.plugin.spring.AvailableToPlugins;
import com.atlassian.sal.api.timezone.TimeZoneManager;
import com.atlassian.sal.api.user.UserKey;
import com.atlassian.stash.internal.user.InternalUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.TimeZone;

import static java.util.Objects.requireNonNull;

/**
 * @since 4.6
 */
@AvailableToPlugins(TimeZoneManager.class)
@Component
public class DefaultTimeZoneManager implements TimeZoneManager {

    private final InternalUserService userService;
    private final TimeZoneService timeZoneService;

    @Autowired
    public DefaultTimeZoneManager(InternalUserService userService, TimeZoneService timeZoneService) {
        this.userService = userService;
        this.timeZoneService = timeZoneService;
    }

    @Nonnull
    @Override
    public TimeZone getUserTimeZone() {
        return TimeZone.getTimeZone(timeZoneService.getTimeZone());
    }

    @Nonnull
    @Override
    public TimeZone getUserTimeZone(@Nonnull UserKey userKey) {
        requireNonNull(userKey, "userKey");

        ApplicationUser user = userService.getUserByKey(userKey);
        if (user == null) {
            return getDefaultTimeZone();
        } else {
            return TimeZone.getTimeZone(timeZoneService.getTimeZone(user));
        }
    }

    @Nonnull
    @Override
    public TimeZone getDefaultTimeZone() {
        return TimeZone.getTimeZone(timeZoneService.getDefaultTimeZone());
    }
}
