package com.atlassian.bitbucket.scm;

import com.atlassian.bitbucket.commit.AbstractCommitRequest;
import com.atlassian.bitbucket.commit.Commit;
import com.atlassian.bitbucket.commit.LastModifiedContext;
import com.atlassian.bitbucket.commit.LastModifiedRequest;

import javax.annotation.Nonnull;

/**
 * Describes a {@link #getCommitId starting commit} to traverse from, searching for the last commit to modify
 * files in the {@link #getPath requested path}.
 * <p>
 * The {@link #getCommitId() starting commit} is used to:
 * <ul>
 *     <li>List the files in the {@link #getPath requested path}</li>
 *     <li>Provide the anchor for traversing history to search for modifications to the listed files</li>
 * </ul>
 * <p>
 * If the {@link #getPath requested path} is {@code null}, {@code ""} or {@code "/"}, it will be treated as
 * a reference to the repository's root directory.
 *
 * @since 4.6
 */
public class LastModifiedCommandParameters extends AbstractCommitCommandParameters {

    private final int maxMessageLength;

    private LastModifiedCommandParameters(Builder builder) {
        super(builder);

        this.maxMessageLength = builder.maxMessageLength;
    }

    /**
     * @return the maximum length to read for {@link Commit#getMessage() commit messages}; if set, messages
     *         longer than this will be truncated; -1 indicates unlimited message length
     */
    public int getMaxMessageLength() {
        return maxMessageLength;
    }

    /**
     * Assembles a {@link LastModifiedContext} from these parameters.
     *
     * @return a {@link LastModifiedContext} describing these parameters
     */
    @Nonnull
    public LastModifiedContext toContext() {
        return new LastModifiedContext.Builder(getCommitId())
                .path(getPath())
                .build();
    }

    public static class Builder extends AbstractCommitParametersBuilder<Builder> {

        private int maxMessageLength;

        public Builder(@Nonnull String commitId) {
            commitId(commitId);

            maxMessageLength = AbstractCommitRequest.UNLIMITED_MESSAGE_LENGTH;
        }

        public Builder(@Nonnull LastModifiedRequest request) {
            super(request);

            maxMessageLength = request.getMaxMessageLength();
        }

        @Nonnull
        public LastModifiedCommandParameters build() {
            return new LastModifiedCommandParameters(this);
        }

        @Nonnull
        @Override
        public Builder commitId(@Nonnull String value) {
            return super.commitId(requireNonBlank(value, "commitId"));
        }

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

            return self();
        }

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