package com.atlassian.bitbucket.mesh.throttle;

import javax.annotation.Nonnull;
import java.util.OptionalLong;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Settings for the {@link ThrottlingStrategy#FIXED fixed throttling strategy}
 */
class FixedResourceThrottleStrategy implements ResourceThrottleStrategy {

    private final int acquireTimeoutSeconds;
    private final ThrottledResource resource;
    private final int ticketLimit;

    FixedResourceThrottleStrategy(ThrottledResource resource, int acquireTimeoutSeconds, int ticketLimit) {
        this.acquireTimeoutSeconds = acquireTimeoutSeconds;
        this.resource = resource;
        this.ticketLimit = ticketLimit;
    }

    @Nonnull
    @Override
    public SemaphoreTicketBucket create() {
        return new SemaphoreTicketBucket(resource, ticketLimit, acquireTimeoutSeconds, SECONDS);
    }

    @Nonnull
    @Override
    public OptionalLong getUpdateInterval(@Nonnull TimeUnit timeUnit) {
        return OptionalLong.empty();
    }

    @Override
    public void update(@Nonnull SemaphoreTicketBucket bucket) {
        bucket.setAcquireTimeoutMillis(SECONDS.toMillis(acquireTimeoutSeconds));
        bucket.setPermits(ticketLimit);
    }

    @Override
    public String toString() {
        return "[resource = " + resource.getId() + ", tickets = " + ticketLimit +
               ", acquire timeout = " + acquireTimeoutSeconds + "s]";
    }

    int getAcquireTimeoutSeconds() {
        return acquireTimeoutSeconds;
    }

    int getTicketLimit() {
        return ticketLimit;
    }
}
