package com.atlassian.bitbucket.mesh.git.fetch;

import com.atlassian.util.profiling.Ticker;
import com.atlassian.util.profiling.Timers;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.file.Path;

import static java.util.Objects.requireNonNull;

public class TimedRefFetchStrategy implements RefFetchStrategy {

    private final RefFetchStrategy delegate;

    public TimedRefFetchStrategy(RefFetchStrategy delegate) {
        this.delegate = requireNonNull(delegate, "delegate");
    }

    public static RefFetchStrategy time(@Nullable RefFetchStrategy strategy) {
        return strategy == null ? null : new TimedRefFetchStrategy(strategy);
    }

    @Override
    public String fetch(@Nonnull RefFetchParameters parameters, @Nonnull Path workTree) {
        try (Ticker ignored = Timers.start("git: fetch ref " + parameters.getToRepository())) {
            return delegate.fetch(parameters, workTree);
        }
    }

    @Override
    public void updateRef(@Nonnull RefFetchParameters parameters, @Nonnull String mergeHash) {
        try (Ticker ignored = Timers.start("git: update ref " + parameters.getToRepository())) {
            delegate.updateRef(parameters, mergeHash);
        }
    }
}
