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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

import static java.util.Objects.requireNonNull;

public abstract class AbstractObjectGitCatFileBuilder<T extends ObjectGitCatFileBuilder<T>>
        extends AbstractGitProcessBuilder<T>
        implements ObjectGitCatFileBuilder<T> {

    private final CatFileFormat format;

    private String object;

    public AbstractObjectGitCatFileBuilder(GitProcessBuilder builder, CatFileFormat format) {
        super(builder);

        this.format = format;
    }

    @Nonnull
    @Override
    public T object(@Nonnull String value) {
        requireNonNull(value, "object");

        if (value.indexOf(':') == -1) {
            //If the object ID doesn't contain a :, treat it as a SHA or a ref ID and trim both leading
            //and trailing whitespace. This will reject values that are only whitespace
            object = requireNonBlank(value, "object");
        } else {
            //If the object ID contains a :, trim leading whitespace but not trailing. The value after
            //the : is treated as a path, and some projects use paths with trailing whitespace
            object = StringUtils.stripStart(value, null);
        }

        return self();
    }

    @Nonnull
    @Override
    public T object(@Nonnull String rev, String file) {
        return object(requireNonBlank(rev, "rev") + ":" + StringUtils.defaultString(file));
    }

    @Override
    protected void applyArguments() {
        builder.argument(format.getFlag());
        builder.rawArgument(object); //The object(...) methods trim, so pass the object value verbatim here
    }
}
