package com.atlassian.bitbucket.avatar;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * An {@link CacheableAvatarSupplier} implementation which delegates to an {@link AvatarSupplier}, storing the avatar's
 * {@link #getTimestamp() modification timestamp} separately. This class can be used to promote an ordinary
 * {@link AvatarSupplier} to a {@link CacheableAvatarSupplier}.
 */
public class DelegatingCacheableAvatarSupplier implements CacheableAvatarSupplier {

    private final AvatarSupplier supplier;
    private final long timestamp;

    /**
     * Constructs a new {@code DelegatingCacheableAvatarSupplier} with an {@link #TIMESTAMP_UNKNOWN unknown} timestamp.
     *
     * @param supplier the {@link AvatarSupplier} containing the avatar's content type and {@code InputStream}
     * @see #DelegatingCacheableAvatarSupplier(AvatarSupplier, long)
     * @see #TIMESTAMP_UNKNOWN
     */
    public DelegatingCacheableAvatarSupplier(@Nonnull AvatarSupplier supplier) {
        this(supplier, TIMESTAMP_UNKNOWN);
    }

    /**
     * Constructs a new {@code DelegatingCacheableAvatarSupplier} with the provided {@code timestamp}.
     *
     * @param supplier  the {@link AvatarSupplier} containing the avatar's content type and {@code InputStream}
     * @param timestamp the avatar's modification timestamp, which may be {@link #TIMESTAMP_UNKNOWN} if no modification
     *                  timestamp is known, or {@link #TIMESTAMP_ETERNAL} if the avatar is unmodifiable
     */
    public DelegatingCacheableAvatarSupplier(@Nonnull AvatarSupplier supplier, long timestamp) {
        this.supplier = checkNotNull(supplier, "supplier");
        this.timestamp = timestamp;
    }

    @Override
    public String getContentType() {
        return supplier.getContentType();
    }

    @Nonnull
    @Override
    public InputStream open() throws IOException {
        return supplier.open();
    }

    @Override
    public long getTimestamp() {
        return timestamp;
    }
}
