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

import com.atlassian.bitbucket.mesh.git.GitRepositoryLayout;
import com.atlassian.bitbucket.mesh.git.builder.GitProcess;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilderSupport;
import com.atlassian.bitbucket.mesh.process.handler.LoggingStdioHandler;
import com.atlassian.bitbucket.mesh.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;

abstract class AbstractGcOperation implements GcOperation {

    protected final Logger log = LoggerFactory.getLogger(getClass());
    protected final Repository repository;
    protected final GitRepositoryLayout repositoryLayout;

    protected AbstractGcOperation(Repository repository, GitRepositoryLayout repositoryLayout) {
        this.repository = repository;
        this.repositoryLayout = repositoryLayout;
    }

    protected void runAction(GcContext context, GcActionType action, GitProcessBuilderSupport<?> builder, Duration timeout) {
        runAction(context, action, builder.build(new LoggingStdioHandler(log)), timeout);
    }

    protected void runAction(GcContext context, GcActionType action, GitProcess<?> command, Duration timeout) {
        long start = System.currentTimeMillis();

        log.debug("[{}] Running {} (timeout = {}s)", repository, command, timeout.getSeconds());
        command.setTimeout(timeout);
        boolean failed = true;
        try {
            command.run();
            failed = false;
        } finally {
            context.addAction(new GcAction(action, start, null, failed));
        }
    }
}
