package com.atlassian.bitbucket.event.user;

import com.atlassian.analytics.api.annotations.EventName;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.event.api.AsynchronousPreferred;

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

import static java.util.Optional.ofNullable;

@AsynchronousPreferred
@EventName("stash.user.time.zone.changed")
public class UserTimeZoneChangedEvent extends UserAttributeChangedEvent {

    private final String oldZoneId;
    private final String newZoneId;
    private final Long offset;

    public UserTimeZoneChangedEvent(@Nonnull Object source, @Nonnull ApplicationUser updatedUser,
                                    @Nullable String oldZoneId, @Nullable String newZoneId) {
        super(source, updatedUser);
        this.oldZoneId = oldZoneId;
        this.newZoneId = newZoneId;
        offset = getOffsetInMinutes(newZoneId);
    }

    @Nonnull
    public Optional<String> getOldZoneId() {
        return ofNullable(oldZoneId);
    }

    @Nonnull
    public Optional<String> getNewZoneId() {
        return ofNullable(newZoneId);
    }

    @Nullable
    public Long getOffset() {
        return offset;
    }

    @Nullable
    private static Long getOffsetInMinutes(String zoneId) {
        if (zoneId != null) {
            return TimeUnit.SECONDS.toMinutes(LocalDateTime.now().atZone(ZoneId.of(zoneId)).getOffset().getTotalSeconds());
        } else {
            return null;
        }
    }
}
