package com.atlassian.bitbucket.mesh.client;

import com.atlassian.bitbucket.mesh.AbstractWiredTest;
import com.atlassian.bitbucket.mesh.TestHelper;
import com.atlassian.bitbucket.mesh.git.GitAgent;
import com.atlassian.bitbucket.mesh.git.ref.Branch;
import com.atlassian.bitbucket.mesh.network.MeshManager;
import com.atlassian.bitbucket.mesh.network.MeshNode;
import com.atlassian.bitbucket.mesh.repository.ManagedRepository;
import com.atlassian.bitbucket.mesh.test.annotation.DirtiesRepo;
import com.atlassian.bitbucket.mesh.test.annotation.Repo;
import org.junit.Test;

import javax.annotation.Resource;

import static com.atlassian.bitbucket.mesh.git.GitObjectType.COMMIT;
import static org.junit.Assert.*;

public class GrpcMeshClientTest extends AbstractWiredTest {

    @Resource
    private GitAgent agent;
    @Resource
    private GrpcMeshClient client;
    @Resource
    private MeshManager meshManager;
    @Repo
    private ManagedRepository repository;
    @Resource
    private TestHelper testHelper;

    @DirtiesRepo
    @Test
    public void testFetchObjects() {
        //Introduce new objects to one of the remote replica
        MeshNode replica = meshManager.getNodes().stream()
                .filter(node -> !node.isLocal())
                .findAny()
                .orElse(null);
        assertNotNull("Replica not found", replica);

        String commitId = testHelper.createCommit(replica, repository.getId());
        //It should _not_ exist in the local repository
        assertNull("Commit found too soon", testHelper.getObjectType(null, repository, commitId));

        //Fetch the objects from the replica
        Branch head = agent.resolveHead(repository);
        client.fetchObjects(replica, repository, new FetchObjectsParameters.Builder()
                .includes(commitId)
                .excludes(head.getLatestCommit())
                .build());

        //Verify that the object now exists in repository as well
        //It should now exist in the local repository
        assertEquals("Commit not found", COMMIT, testHelper.getObjectType(null, repository, commitId));
    }
}
