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

import com.atlassian.bitbucket.mesh.git.commit.Commit;
import com.atlassian.bitbucket.mesh.util.BuilderSupport;
import com.google.common.collect.ImmutableList;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Objects;

import static java.util.Objects.requireNonNull;

public class Changeset {

    private final List<Change> changes;
    private final String fromCommitId;
    private final Commit toCommit;

    private Changeset(Builder builder) {
        changes = builder.changes.build();
        fromCommitId = builder.fromCommitId;
        toCommit = builder.toCommit;
    }

    @Nonnull
    public List<Change> getChanges() {
        return changes;
    }

    @Nullable
    public String getFromCommitId() {
        return fromCommitId;
    }

    @Nonnull
    public Commit getToCommit() {
        return toCommit;
    }

    public static class Builder extends BuilderSupport {

        private final ImmutableList.Builder<Change> changes;
        private final Commit toCommit;

        private String fromCommitId;

        public Builder(@Nonnull Commit toCommit) {
            this.toCommit = requireNonNull(toCommit, "toCommit");

            changes = ImmutableList.builder();
        }

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

        @Nonnull
        public Builder change(@Nonnull Change value) {
            changes.add(requireNonNull(value, "change"));

            return this;
        }

        @Nonnull
        public Builder changes(@Nonnull Iterable<Change> values) {
            addIf(Objects::nonNull, changes, values);

            return this;
        }

        @Nonnull
        public Builder fromCommitId(@Nullable String value) {
            fromCommitId = value;

            return this;
        }
    }
}
