package com.atlassian.bitbucket.mesh.management;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcTicketInfo;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTicketInfo.Builder;
import com.atlassian.bitbucket.mesh.throttle.TicketSummary;

import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.Locale;

import static java.util.Objects.requireNonNull;

class TicketInfo {

    private final TicketSummary summary;

    TicketInfo(@Nonnull TicketSummary summary) {
        this.summary = requireNonNull(summary, "summary");
    }

    @Nonnull
    RpcTicketInfo toTicketInfo() {
        Builder builder = RpcTicketInfo.newBuilder()
                .setAvailable(summary.getAvailable())
                .setQueuedRequests(summary.getQueuedRequests())
                .setResource(summary.getResource().getId().toLowerCase(Locale.ROOT))
                .setTotal(summary.getTotal())
                .setUsed(summary.getUsed());

        Instant lastRejection = summary.getLastRejection();
        Instant oldestQueued = summary.getOldestQueuedRequest();

        if (lastRejection != null) {
            builder.setLastRejection(lastRejection.toEpochMilli());
        }

        if (oldestQueued != null) {
            builder.setOldestQueuedRequest(oldestQueued.toEpochMilli());
        }

        return builder.build();
    }
}
