package de.fhg.iais.cortex.services.entity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.apache.solr.client.solrj.SolrServerException;
import org.jdom.JDOMException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;

import com.google.common.collect.Lists;

import de.fhg.iais.cortex.entity.EntitySearcher;
import de.fhg.iais.cortex.entity.types.EntityResult;
import de.fhg.iais.cortex.entity.types.PersonSearchResult;
import de.fhg.iais.cortex.search.types.Cluster;
import de.fhg.iais.cortex.search.types.Query;
import de.fhg.iais.cortex.search.types.SearchResults;

public class EntityServiceImplTest {

    private IEntityService service;
    private EntitySearcher searcherMock;

    @Before
    public void setup() throws JDOMException, IOException, SolrServerException {
        this.searcherMock = Mockito.mock(EntitySearcher.class);
        this.service = new EntityServiceImpl(this.searcherMock);
    }

    @Test
    public void testSearch() {
        PersonSearchResult result = new PersonSearchResult.Builder("uri", "label", 10).build();

        SearchResults<EntityResult> results = new SearchResults<EntityResult>();
        Cluster<EntityResult> cluster = new Cluster<EntityResult>("single");
        cluster.addAll(Lists.<EntityResult> newArrayList(result));
        results.addCluster(cluster);

        Mockito.when(this.searcherMock.search(Matchers.<Query> any())).thenReturn(results);

        SearchResults<EntityResult> entityResults = this.service.search(new Query(Query.ALL_QUERY));

        assertNotNull(entityResults);
        Cluster<EntityResult> entityCluster = entityResults.getResults().get(0);
        assertNotNull(entityCluster);
        assertEquals(cluster, entityCluster);
        assertEquals(1, cluster.getNumberOfDocs());
        assertEquals("uri", entityCluster.getDoc(0).getId());
        assertEquals("label", ((PersonSearchResult) entityCluster.getDoc(0)).getPreferredName());
        assertEquals(10, ((PersonSearchResult) entityCluster.getDoc(0)).getCount());
        assertTrue(((PersonSearchResult) entityCluster.getDoc(0)).getVariantName().isEmpty());
    }
}