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

import com.atlassian.bitbucket.mesh.git.GitTimers;
import com.atlassian.bitbucket.mesh.git.porcelain.WorkTreeParameters;
import com.atlassian.util.profiling.Ticker;

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

import static java.util.Objects.requireNonNull;

public class TimedMergeStrategy implements MergeStrategy {

    private final MergeStrategy delegate;

    public TimedMergeStrategy(MergeStrategy delegate) {
        this.delegate = requireNonNull(delegate, "delegate");
    }

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

    @Nonnull
    @Override
    public WorkTreeParameters.Builder customizeWorkTree(@Nonnull WorkTreeParameters.Builder builder) {
        return delegate.customizeWorkTree(builder);
    }

    @Override
    public void merge(@Nonnull MergeParameters parameters, @Nonnull Path workTree) {
        try (Ticker ignored = GitTimers.MERGE.start(parameters.getFrom().getLatestCommit())) {
            delegate.merge(parameters, workTree);
        }
    }
}
