package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.git.content.Change;
import com.atlassian.bitbucket.mesh.git.content.ChangeCallback;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcGetPullRequestChangesResponseFragment;
import io.grpc.stub.StreamObserver;

import javax.annotation.Nonnull;

class ObserverPullRequestChangeCallback
        extends AbstractObserverCallback<RpcGetPullRequestChangesResponseFragment>
        implements ChangeCallback {

    private final RpcGetPullRequestChangesResponseFragment.Builder fragment;

    ObserverPullRequestChangeCallback(StreamObserver<RpcGetPullRequestChangesResponseFragment> observer) {
        super(observer);

        fragment = RpcGetPullRequestChangesResponseFragment.newBuilder();
    }

    @Override
    public void onChange(@Nonnull Change change) {
        fragment.addChanges(change.toChange());
        if (fragment.getChangesCount() >= FRAGMENT_SIZE) {
            sendFragment();
        }
    }

    private void sendFragment() {
        observer.onNext(fragment.build());
        fragment.clearChanges();
    }

    void onEnd() {
        sendLastFragment();
        observer.onCompleted();
    }

    private void sendLastFragment() {
        if (fragment.getChangesCount() > 0) {
            sendFragment();
        }
    }
}
