package eu.dnetlib.data.transform;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.dom4j.DocumentException;
import org.junit.Before;
import org.junit.Test;

import com.google.protobuf.InvalidProtocolBufferException;
import com.googlecode.protobuf.format.JsonFormat;

import eu.dnetlib.data.mapreduce.util.OafTest;
import eu.dnetlib.data.proto.KindProtos.Kind;
import eu.dnetlib.data.proto.OafProtos.Oaf;
import eu.dnetlib.data.proto.OafProtos.OafEntity;
import eu.dnetlib.functionality.index.solr.feed.InputDocumentFactory;

public class SolrProtoMapperTest {

	private static final Log log = LogFactory.getLog(SolrProtoMapper.class); // NOPMD by marko on 11/24/08 5:02 PM
	private String fields;

	@Before
	public void setUp() throws IOException {
		final StringWriter sw = new StringWriter();
		IOUtils.copy(getClass().getResourceAsStream("fields.xml"), sw);
		fields = sw.toString();
		assertNotNull(fields);
		assertFalse(fields.isEmpty());

		log.info(fields);
	}

	@Test
	public void testProto2SolrDocument() throws DocumentException, InvalidProtocolBufferException {
		final SolrProtoMapper mapper = new SolrProtoMapper(fields);

		assertNotNull(mapper);

		final OafEntity.Builder entity = OafTest.getResultBuilder("01");
		entity.addChildren(OafTest.getResultBuilder("01_children"));

		final Oaf oaf = OafTest.embed(entity.build(), Kind.entity).getOaf();

		assertNotNull(oaf.getEntity().getChildrenList());
		assertFalse(oaf.getEntity().getChildrenList().isEmpty());

		log.info("byte[] size: " + oaf.toByteArray().length);

		log.info("json size:   " + JsonFormat.printToString(oaf).length());

		log.info("base64 size: " + Base64.encodeBase64String(oaf.toByteArray()).length());

		final byte[] decodeBase64 = Base64.decodeBase64(Base64.encodeBase64String(oaf.toByteArray()));

		log.info("decoded: " + JsonFormat.printToString(Oaf.parseFrom(decodeBase64)));

		final SolrInputDocument doc = mapper.map(oaf, InputDocumentFactory.getParsedDateField("2015-02-15"), "asd", "action-set");

		assertNotNull(doc);

		for (final SolrInputField f : doc.values()) {
			log.info(f);
		}
	}
}
