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

import com.atlassian.bitbucket.mesh.git.AbstractParameters;
import com.atlassian.bitbucket.mesh.git.builder.revlist.CommitPumpSettings;
import com.atlassian.bitbucket.mesh.repository.Repository;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.isBlank;

public abstract class AbstractGetCommitParameters extends AbstractParameters {

    private final String commitId;
    private final int maxMessageLength;
    private final String path;
    private final Repository repository;

    protected AbstractGetCommitParameters(AbstractBuilder<?, ?> builder) {
        super(builder);

        commitId = builder.commitId;
        maxMessageLength = Math.max(builder.maxMessageLength, CommitPumpSettings.UNLIMITED_MESSAGE_LENGTH);
        path = builder.path;
        repository = builder.repository;
    }

    @Nonnull
    public String getCommitId() {
        return commitId;
    }

    public int getMaxMessageLength() {
        return maxMessageLength;
    }

    @Nullable
    public String getPath() {
        return path;
    }

    @Nonnull
    public Repository getRepository() {
        return repository;
    }

    public abstract static class AbstractBuilder<B extends AbstractBuilder<B, R>, R extends AbstractGetCommitParameters>
            extends AbstractParameters.AbstractBuilder<B, R> {

        private final String commitId;
        private final Repository repository;

        private int maxMessageLength;
        private String path;

        public AbstractBuilder(@Nonnull Repository repository, @Nonnull String commitId) {
            this.commitId = requireNonBlank(commitId, "commitId");
            this.repository = requireNonNull(repository, "repository");
        }

        public AbstractBuilder(@Nonnull AbstractGetCommitParameters parameters) {
            super(parameters);

            commitId = parameters.getCommitId();
            maxMessageLength = parameters.getMaxMessageLength();
            path = parameters.getPath();
            repository = parameters.getRepository();
        }

        @Nonnull
        public B maxMessageLength(int value) {
            maxMessageLength = value;

            return self();
        }

        @Nonnull
        public B path(@Nullable String value) {
            path = isBlank(value) ? null : value; //Replace blank/empty with null, but don't trim other values

            return self();
        }
    }
}
