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

import com.atlassian.bitbucket.mesh.git.builder.AbstractGitProcessBuilder;
import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;

import javax.annotation.Nonnull;

public class DefaultGitBlameBuilder extends AbstractGitProcessBuilder<GitBlameBuilder> implements GitBlameBuilder {

    private final BlameFormat format;

    private int end;
    private boolean endIsOffset;
    private String file;
    private String rev;
    private int start;

    public DefaultGitBlameBuilder(GitProcessBuilder builder, BlameFormat format) {
        super(builder);

        this.format = format;
    }

    @Nonnull
    @Override
    public GitBlameBuilder clearRange() {
        end = start = 0;
        endIsOffset = false;

        return self();
    }

    @Nonnull
    @Override
    public DefaultGitBlameBuilder file(String value) {
        file = value;

        return self();
    }

    @Nonnull
    @Override
    public GitBlameBuilder range(int start, int end, boolean endIsOffset) {
        this.end = end;
        this.endIsOffset = endIsOffset;
        this.start = start;

        return self();
    }

    @Nonnull
    @Override
    public DefaultGitBlameBuilder rev(String value) {
        rev = value;

        return self();
    }

    @Override
    protected void applyArguments() {
        builder.argument(format.getFlag());

        if (start > 0 && end > 0) {
            StringBuilder rangeBuilder = new StringBuilder().append(start).append(",");
            if (endIsOffset) {
                rangeBuilder.append("+");
            }
            rangeBuilder.append(end);

            builder.argument("-L").argument(rangeBuilder.toString());
        }
        if (rev != null) {
            builder.commitish(rev);
        }
        if (file != null) {
            builder.argument("--").rawArgument(file);
        }
    }

    @Nonnull
    @Override
    protected DefaultGitBlameBuilder self() {
        return this;
    }
}
