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

import com.atlassian.bitbucket.mesh.process.ProcessCreator;
import com.atlassian.bitbucket.mesh.process.ProcessParameters;
import com.google.common.base.Joiner;

import javax.annotation.Nonnull;
import java.time.Duration;
import java.util.concurrent.Future;

import static java.util.Objects.requireNonNull;

class DefaultGitProcess<T> implements GitProcess<T> {

    private final ProcessCreator creator;
    private final ProcessParameters<T> parameters;

    DefaultGitProcess(@Nonnull ProcessCreator creator, @Nonnull ProcessParameters<T> parameters) {
        this.creator = requireNonNull(creator, "creator");
        this.parameters = requireNonNull(parameters, "creator");
    }

    @Override
    public T run() {
        return creator.run(parameters);
    }

    @Override
    public void setExecutionInterval(@Nonnull Duration duration) {
        parameters.setExecutionInterval(requireNonNull(duration, "duration"));
    }

    @Override
    public void setIdleInterval(@Nonnull Duration duration) {
        parameters.setIdleInterval(requireNonNull(duration, "duration"));
    }

    @Override
    public void setTimeout(@Nonnull Duration duration) {
        parameters.setExecutionInterval(requireNonNull(duration, "duration"));
        parameters.setIdleInterval(duration);
    }

    @Nonnull
    @Override
    public Future<T> start() {
        return creator.start(parameters);
    }

    @Override
    public String toString() {
        return Joiner.on(' ').join(parameters.getArguments());
    }
}
