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

import com.atlassian.bitbucket.mesh.git.ref.RefUpdate;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcPullRequestRefUpdates;

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

import static java.util.Objects.requireNonNull;

public class PullRequestRefUpdates {

    private final PullRequest pullRequest;
    private final RefUpdate fromRefUpdate;
    private final RefUpdate mergeRefUpdate;

    private PullRequestRefUpdates(Builder builder) {
        pullRequest = builder.pullRequest;
        fromRefUpdate = builder.fromRef;
        mergeRefUpdate = builder.mergeRef;
    }

    @Nullable
    public RefUpdate getFromRefUpdate() {
        return fromRefUpdate;
    }

    @Nullable
    public RefUpdate getMergeRefUpdate() {
        return mergeRefUpdate;
    }

    @Nonnull
    public PullRequest getPullRequest() {
        return pullRequest;
    }

    @Nonnull
    public RpcPullRequestRefUpdates toPullRequestRefUpdates() {
        RpcPullRequestRefUpdates.Builder builder = RpcPullRequestRefUpdates.newBuilder()
                .setId(pullRequest.getId())
                .setRepository(pullRequest.getToRef().getRepository().getId());
        if (fromRefUpdate != null) {
            builder.setFromRefUpdate(fromRefUpdate.toRefUpdate());
        }
        if (mergeRefUpdate != null) {
            builder.setMergeRefUpdate(mergeRefUpdate.toRefUpdate());
        }
        return builder.build();
    }

    public static class Builder {

        private final PullRequest pullRequest;

        private RefUpdate fromRef;
        private RefUpdate mergeRef;

        public Builder(@Nonnull PullRequest pullRequest) {
            this.pullRequest = requireNonNull(pullRequest, "pullRequest");
        }

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

        @Nonnull
        public Builder fromRef(@Nullable RefUpdate value) {
            fromRef = value;
            return this;
        }

        @Nonnull
        public Builder mergeRef(@Nullable RefUpdate value) {
            mergeRef = value;
            return this;
        }
    }
}
