
package eu.dnetlib.dhp.oa.graph.dump.skgif;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;

import javax.validation.constraints.AssertTrue;

import org.apache.commons.io.FileUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.api.java.function.ForeachFunction;
import org.apache.spark.api.java.function.MapFunction;
import org.apache.spark.api.java.function.MapGroupsFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import eu.dnetlib.dhp.oa.graph.dump.skgif.beans.EmitPerManifestation;
import eu.dnetlib.dhp.oa.graph.dump.skgif.beans.RelationPerProduct;
import eu.dnetlib.dhp.oa.model.graph.Relation;
import eu.dnetlib.dhp.skgif.model.*;
import eu.dnetlib.dhp.utils.DHPUtils;

/**
 * @author miriam.baglioni
 * @Date 20/02/24
 */
public class DumpResultTest {
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	private static SparkSession spark;

	private static Path workingDir;

	private static final Logger log = LoggerFactory.getLogger(DumpResultTest.class);

	@BeforeAll
	public static void beforeAll() throws IOException {
		workingDir = Files.createTempDirectory(DumpResultTest.class.getSimpleName());
		log.info("using work dir {}", workingDir);

		SparkConf conf = new SparkConf();
		conf.setAppName(DumpResultTest.class.getSimpleName());

		conf.setMaster("local[*]");
		conf.set("spark.driver.host", "localhost");
		conf.set("hive.metastore.local", "true");
		conf.set("spark.ui.enabled", "false");
		conf.set("spark.sql.warehouse.dir", workingDir.toString());
		conf.set("hive.metastore.warehouse.dir", workingDir.resolve("warehouse").toString());

		spark = SparkSession
			.builder()
			.appName(DumpResultTest.class.getSimpleName())
			.config(conf)
			.getOrCreate();
	}

	@AfterAll
	public static void afterAll() throws IOException {
		FileUtils.deleteDirectory(workingDir.toFile());
		spark.stop();
	}

	@Test
	public void testEmitFromResult() throws Exception {
		final String sourcePath = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/graph/")
			.getPath();

		final String workingDir = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/workingDir/")
			.getPath();

		DumpResult
			.main(
				new String[] {
					"-isSparkSessionManaged", Boolean.FALSE.toString(),
					"-sourcePath", sourcePath,
					"-workingDir", workingDir

				});

		final JavaSparkContext sc = JavaSparkContext.fromSparkContext(spark.sparkContext());

		JavaRDD<RelationPerProduct> relation = sc
			.textFile(workingDir + "/aggrelation")
			.map(item -> OBJECT_MAPPER.readValue(item, RelationPerProduct.class));

		Dataset<RelationPerProduct> relationDataset = spark
			.createDataset(relation.rdd(), Encoders.bean(RelationPerProduct.class));

		relationDataset.show(false);
		Assertions.assertEquals(7, relationDataset.count());
		RelationPerProduct temp = relationDataset
			.filter(
				(FilterFunction<RelationPerProduct>) r -> r
					.getResultId()
					.equalsIgnoreCase("50|DansKnawCris::20c414a3b1c742d5dd3851f1b67df2d9"))
			.first();
		Assertions
			.assertEquals(
				3, temp.getFunding().size() + temp.getRelatedProduct().size() + temp.getOrganizations().size());
		Assertions.assertEquals(1, temp.getFunding().size());
		Assertions.assertEquals(2, temp.getRelatedProduct().size());
		Assertions
			.assertEquals(
				1,
				temp
					.getRelatedProduct()
					.get(RelationType.SUPPLEMENT.label)
					.size());
		Assertions
			.assertEquals(
				1,
				temp
					.getRelatedProduct()
					.get(RelationType.DOCUMENTS.label)
					.size());

		JavaRDD<ResearchProduct> researchProduct = sc
			.textFile(workingDir.toString() + "/publication/researchproduct")
			.map(item -> OBJECT_MAPPER.readValue(item, ResearchProduct.class));

		org.apache.spark.sql.Dataset<ResearchProduct> researchProductDataset = spark
			.createDataset(researchProduct.rdd(), Encoders.bean(ResearchProduct.class));

		Assertions
			.assertEquals(
				1,
				researchProductDataset
					.filter(
						(FilterFunction<ResearchProduct>) p -> p
							.getLocal_identifier()
							.equalsIgnoreCase(
								Utils
									.getIdentifier(
										Prefixes.RESEARCH_PRODUCT,
										"50|DansKnawCris::0224aae28af558f21768dbc6439c7a95")))
					.count());
		ResearchProduct product = researchProductDataset
			.filter(
				(FilterFunction<ResearchProduct>) p -> p
					.getLocal_identifier()
					.equalsIgnoreCase(
						Utils
							.getIdentifier(
								Prefixes.RESEARCH_PRODUCT, "50|DansKnawCris::0224aae28af558f21768dbc6439c7a95")))
			.first();
		Assertions.assertEquals(2, product.getRelevant_organizations().size());
		Assertions.assertEquals(1, product.getFunding().size());
		Assertions.assertEquals(0, product.getRelated_products().size());
		Assertions.assertEquals(1, product.getContributions().size());
		Assertions.assertEquals(2, product.getManifestations().size());

		researchProductDataset.show(false);
		researchProductDataset
			.foreach((ForeachFunction<ResearchProduct>) rp -> System.out.println(OBJECT_MAPPER.writeValueAsString(rp)));

	}

	@Test
	public void testEmitFromDedupedResult() throws Exception {
		final String sourcePath = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/graph_complete_entities/")
			.getPath();

		final String workingDir = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/workingDir_complete_entities/")
			.getPath();

		DumpResult
			.main(
				new String[] {
					"-isSparkSessionManaged", Boolean.FALSE.toString(),
					"-sourcePath", sourcePath,
					"-workingDir", workingDir,
					"-outputPath", workingDir

				});

		final JavaSparkContext sc = JavaSparkContext.fromSparkContext(spark.sparkContext());

		JavaRDD<ResearchProduct> researchProduct = sc
			.textFile(workingDir.toString() + "ResearchProduct")
			.map(item -> OBJECT_MAPPER.readValue(item, ResearchProduct.class));

		org.apache.spark.sql.Dataset<ResearchProduct> researchProductDataset = spark
			.createDataset(researchProduct.rdd(), Encoders.bean(ResearchProduct.class));

		Assertions.assertEquals(1, researchProductDataset.count());

		ResearchProduct rp = researchProductDataset.first();

		// check the local identifier
		Assertions.assertEquals("product_____::e22a152ab43b9215d14ece613f76ec84", rp.getLocal_identifier());

		// check the pids of the result
		Assertions.assertEquals(3, rp.getIdentifiers().size());
		Assertions
			.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("doi")).count());
		Assertions
			.assertEquals(
				"10.1007/s40199-021-00403-x",
				rp
					.getIdentifiers()
					.stream()
					.filter(p -> p.getScheme().equalsIgnoreCase("doi"))
					.collect(Collectors.toList())
					.get(0)
					.getValue());
		Assertions
			.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("pmid")).count());
		Assertions
			.assertEquals(
				"34327650",
				rp
					.getIdentifiers()
					.stream()
					.filter(p -> p.getScheme().equalsIgnoreCase("pmid"))
					.collect(Collectors.toList())
					.get(0)
					.getValue());
		Assertions
			.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("pmc")).count());
		Assertions
			.assertEquals(
				"PMC8602609",
				rp
					.getIdentifiers()
					.stream()
					.filter(p -> p.getScheme().equalsIgnoreCase("pmc"))
					.collect(Collectors.toList())
					.get(0)
					.getValue());

		// check the title
		Assertions.assertEquals(1, rp.getTitles().keySet().size());
		Assertions.assertTrue(rp.getTitles().keySet().contains("none"));
		Assertions.assertEquals(1, rp.getTitles().get("none").size());

		// check abstract
		Assertions.assertEquals(1, rp.getAbstracts().keySet().size());
		Assertions.assertTrue(rp.getAbstracts().keySet().contains("none"));
		Assertions.assertEquals(1, rp.getAbstracts().get("none").size());

		// check type
		Assertions.assertEquals("literature", rp.getProduct_type());

		// check topics
		Assertions.assertEquals(3, rp.getTopics().size());
		Assertions
			.assertTrue(
				rp
					.getTopics()
					.stream()
					.anyMatch(
						t -> t
							.getTopic()
							.getValue()
							.equalsIgnoreCase(Prefixes.TOPIC.label + DHPUtils.md5("FOSSustained delivery"))));

		// check contributions
		Assertions.assertEquals(4, rp.getContributions().size());
		Assertions
			.assertEquals(
				3,
				rp
					.getContributions()
					.stream()
					.filter(c -> c.getPerson().getLocal_identifier().startsWith("person"))
					.count());
		Assertions
			.assertEquals(
				1,
				rp
					.getContributions()
					.stream()
					.filter(c -> c.getPerson().getLocal_identifier().startsWith("temp"))
					.count());
		rp.getContributions().forEach(c -> Assertions.assertTrue(c.getDeclared_affiliation() == null));
		Assertions
			.assertEquals(
				1,
				rp
					.getContributions()
					.stream()
					.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0001-8284-6269true")))
					.collect(Collectors.toList())
					.get(0)
					.getRank());
		Assertions
			.assertEquals(
				2,
				rp
					.getContributions()
					.stream()
					.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0002-0940-893xtrue")))
					.collect(Collectors.toList())
					.get(0)
					.getRank());
		Assertions
			.assertEquals(
				3,
				rp
					.getContributions()
					.stream()
					.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0001-5291-577xtrue")))
					.collect(Collectors.toList())
					.get(0)
					.getRank());
		Assertions
			.assertEquals(
				4,
				rp
					.getContributions()
					.stream()
					.filter(
						c -> c
							.getPerson()
							.equals(
								Utils
									.getIdentifier(
										Prefixes.TEMPORARY_PERSON,
										"50|doi_dedup___::0000661be7c602727bae9690778b16514")))
					.collect(Collectors.toList())
					.get(0)
					.getRank());
		researchProductDataset.show(10, 100, true);

		// check manifestation 1
		Assertions.assertEquals(3, rp.getManifestations().size());
		Manifestation manifestation = rp
			.getManifestations()
			.stream()
			.filter(
				m -> m
					.getHosting_datasource()
					.equals(
						Utils.getIdentifier(Prefixes.DATASOURCE, "10|doajarticles::6107489403b31fc7cf37cb7fda35f7f1")))
			.collect(Collectors.toList())
			.get(0);
		Assertions.assertEquals("Article", manifestation.getProduct_local_type());
		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
		Assertions.assertEquals(1, manifestation.getDates().size());
		Assertions.assertEquals("2021-07-29", manifestation.getDates().get(0).getValue());
		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
		Assertions.assertEquals(PeerReview.PEER_REVIEWED.label, manifestation.getPeer_review());
		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
		Assertions.assertEquals(AccessRight.CLOSED.label, manifestation.getAccess_right());
		Assertions.assertEquals("Springer Nature TDM", manifestation.getLicence());
		Assertions.assertEquals("https://doi.org/10.1007/s40199-021-00403-x", manifestation.getUrl());
		Assertions.assertEquals("10.1007/s40199-021-00403-x", manifestation.getPid());
		Assertions.assertTrue(manifestation.getBiblio() != null);
		Biblio biblio = manifestation.getBiblio();
		Assertions.assertTrue(biblio.getEdition() == null);
		Assertions.assertTrue(biblio.getIssue() == null);
		Assertions.assertEquals("Springer Science and Business Media LLC", biblio.getPublisher());
		Assertions.assertEquals("29", biblio.getVolume());
		Assertions.assertEquals("415", biblio.getStart_page());
		Assertions.assertEquals("438", biblio.getEnd_page());

		// check manifestation 2
		manifestation = rp
			.getManifestations()
			.stream()
			.filter(
				m -> m
					.getHosting_datasource()
					.equals(
						Utils.getIdentifier(Prefixes.DATASOURCE, "10|openaire____::55045bd2a65019fd8e6741a755395c8c")))
			.collect(Collectors.toList())
			.get(0);
		Assertions.assertEquals("Article", manifestation.getProduct_local_type());
		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
		Assertions.assertEquals(1, manifestation.getDates().size());
		Assertions.assertEquals("2020-01-03", manifestation.getDates().get(0).getValue());
		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
		Assertions.assertEquals(PeerReview.NON_PEER_REVIEWED.label, manifestation.getPeer_review());
		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
		Assertions.assertEquals(AccessRight.UNAVAILABLE.label, manifestation.getAccess_right());
		Assertions.assertEquals(null, manifestation.getLicence());
		Assertions.assertEquals("https://pubmed.ncbi.nlm.nih.gov/34327650", manifestation.getUrl());
		Assertions.assertEquals("34327650", manifestation.getPid());
		Assertions.assertTrue(manifestation.getBiblio() == null);

		// check manifestation 3
		manifestation = rp
			.getManifestations()
			.stream()
			.filter(
				m -> m
					.getHosting_datasource()
					.equals(
						Utils.getIdentifier(Prefixes.DATASOURCE, "10|opendoar____::8b6dd7db9af49e67306feb59a8bdc52c")))
			.collect(Collectors.toList())
			.get(0);
		Assertions.assertEquals("Other literature type", manifestation.getProduct_local_type());
		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
		Assertions.assertEquals(1, manifestation.getDates().size());
		Assertions.assertEquals("2021-07-29", manifestation.getDates().get(0).getValue());
		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
		Assertions.assertEquals(PeerReview.NON_PEER_REVIEWED.label, manifestation.getPeer_review());
		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
		Assertions.assertEquals(AccessRight.OPEN.label, manifestation.getAccess_right());
		Assertions.assertEquals(null, manifestation.getLicence());
		Assertions.assertEquals("https://europepmc.org/articles/PMC8602609/", manifestation.getUrl());
		Assertions.assertEquals("PMC8602609", manifestation.getPid());
		Assertions.assertTrue(manifestation.getBiblio() == null);

		// check relevant organization
		Assertions.assertEquals(1, rp.getRelevant_organizations().size());
		Assertions
			.assertEquals(
				Prefixes.ORGANIZATION.label + "601e510b1fda7cc6cb03329531502171",
				rp.getRelevant_organizations().get(0));

		// check funding
		Assertions.assertEquals(1, rp.getFunding().size());
		Assertions.assertEquals(Prefixes.GRANT.label + "a7795022763d413f5de59036ebbd0c52", rp.getFunding().get(0));

		// check related products
		Assertions.assertEquals(5, rp.getRelated_products().size());
		Assertions
			.assertEquals(
				4,
				rp
					.getRelated_products()
					.stream()
					.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.CITATION.label))
					.collect(Collectors.toList())
					.get(0)
					.getProduct_list()
					.size());
		Assertions
			.assertEquals(
				1,
				rp
					.getRelated_products()
					.stream()
					.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.DOCUMENTS.label))
					.collect(Collectors.toList())
					.get(0)
					.getProduct_list()
					.size());
		Assertions
			.assertEquals(
				1,
				rp
					.getRelated_products()
					.stream()
					.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.PART.label))
					.collect(Collectors.toList())
					.get(0)
					.getProduct_list()
					.size());
		Assertions
			.assertEquals(
				1,
				rp
					.getRelated_products()
					.stream()
					.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.SUPPLEMENT.label))
					.collect(Collectors.toList())
					.get(0)
					.getProduct_list()
					.size());
		Assertions
			.assertEquals(
				1,
				rp
					.getRelated_products()
					.stream()
					.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.VERSION.label))
					.collect(Collectors.toList())
					.get(0)
					.getProduct_list()
					.size());

	}

	@Test
	public void testEmitFromApi() throws Exception {
		final String sourcePath = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/graphForAPIExample/")
			.getPath();

		final String workingDir = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/workingDirApiExample/")
			.getPath();

		final StructType relationstructureSchema = new StructType()
			.add(
				"dataInfo", new StructType()
					.add("deletedbyinference", DataTypes.BooleanType))
			.add("source", DataTypes.StringType)
			.add("target", DataTypes.StringType)
			.add("relClass", DataTypes.StringType);

		final StructType productSchema = new StructType()
			.add("local_identifier", DataTypes.StringType)
			.add("title", DataTypes.StringType)
			.add("doi", DataTypes.StringType)
			.add("pmcid", DataTypes.StringType)
			.add("arxivid", DataTypes.StringType)
			.add("pmid", DataTypes.StringType);

		Dataset<Row> relation = spark
			.read()
			.schema(relationstructureSchema)
			.json(sourcePath + "relation")
			.filter(
				"datainfo.deletedbyinference != true and " +
					"relclass == '" + RelationType.CITATION.label + "'")
			.drop("dataInfo");

		Dataset<Row> minProduct = spark
			.read()
			.schema(productSchema)
			.json(workingDir + "minProduct");
		relation
			.joinWith(
				minProduct, relation.col("target").equalTo(minProduct.col("local_identifier")))
			.selectExpr("_1.source as sourceResult", "_2.*")

			.show(false);

	}

	@Test
	public void testEmitFromApiDump() throws Exception {
		final String sourcePath = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/graphForAPIExample/")
			.getPath();

		final String workingDir = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/workingDirApiExample/")
			.getPath();

		DumpResult
			.main(
				new String[] {
					"-isSparkSessionManaged", Boolean.FALSE.toString(),
					"-sourcePath", sourcePath,
					"-workingDir", workingDir,
					"-outputPath", workingDir

				});

		final JavaSparkContext sc = JavaSparkContext.fromSparkContext(spark.sparkContext());

		JavaRDD<ResearchProduct> researchProduct = sc
			.textFile(workingDir.toString() + "ResearchProduct")
			.map(item -> OBJECT_MAPPER.readValue(item, ResearchProduct.class));

		researchProduct.foreach(r -> System.out.println(OBJECT_MAPPER.writeValueAsString(r)));

//		org.apache.spark.sql.Dataset<ResearchProduct> researchProductDataset = spark
//				.createDataset(researchProduct.rdd(), Encoders.bean(ResearchProduct.class));

//		Assertions.assertEquals(1, researchProductDataset.count());
//
//		ResearchProduct rp = researchProductDataset.first();
//
//		// check the local identifier
//		Assertions.assertEquals("product_____::e22a152ab43b9215d14ece613f76ec84", rp.getLocal_identifier());
//
//		// check the pids of the result
//		Assertions.assertEquals(3, rp.getIdentifiers().size());
//		Assertions
//				.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("doi")).count());
//		Assertions
//				.assertEquals(
//						"10.1007/s40199-021-00403-x",
//						rp
//								.getIdentifiers()
//								.stream()
//								.filter(p -> p.getScheme().equalsIgnoreCase("doi"))
//								.collect(Collectors.toList())
//								.get(0)
//								.getValue());
//		Assertions
//				.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("pmid")).count());
//		Assertions
//				.assertEquals(
//						"34327650",
//						rp
//								.getIdentifiers()
//								.stream()
//								.filter(p -> p.getScheme().equalsIgnoreCase("pmid"))
//								.collect(Collectors.toList())
//								.get(0)
//								.getValue());
//		Assertions
//				.assertEquals(1, rp.getIdentifiers().stream().filter(p -> p.getScheme().equalsIgnoreCase("pmc")).count());
//		Assertions
//				.assertEquals(
//						"PMC8602609",
//						rp
//								.getIdentifiers()
//								.stream()
//								.filter(p -> p.getScheme().equalsIgnoreCase("pmc"))
//								.collect(Collectors.toList())
//								.get(0)
//								.getValue());
//
//		// check the title
//		Assertions.assertEquals(1, rp.getTitles().keySet().size());
//		Assertions.assertTrue(rp.getTitles().keySet().contains("none"));
//		Assertions.assertEquals(1, rp.getTitles().get("none").size());
//
//		// check abstract
//		Assertions.assertEquals(1, rp.getAbstracts().keySet().size());
//		Assertions.assertTrue(rp.getAbstracts().keySet().contains("none"));
//		Assertions.assertEquals(1, rp.getAbstracts().get("none").size());
//
//		// check type
//		Assertions.assertEquals("literature", rp.getProduct_type());
//
//		// check topics
//		Assertions.assertEquals(3, rp.getTopics().size());
//		Assertions
//				.assertTrue(
//						rp
//								.getTopics()
//								.stream()
//								.anyMatch(
//										t -> t
//												.getTopic()
//												.getValue()
//												.equalsIgnoreCase(Prefixes.TOPIC.label + DHPUtils.md5("FOSSustained delivery"))));
//
//		// check contributions
//		Assertions.assertEquals(4, rp.getContributions().size());
//		Assertions
//				.assertEquals(
//						3,
//						rp
//								.getContributions()
//								.stream()
//								.filter(c -> c.getPerson().getLocal_identifier().startsWith("person"))
//								.count());
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getContributions()
//								.stream()
//								.filter(c -> c.getPerson().getLocal_identifier().startsWith("temp"))
//								.count());
//		rp.getContributions().forEach(c -> Assertions.assertTrue(c.getDeclared_affiliation() == null));
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getContributions()
//								.stream()
//								.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0001-8284-6269true")))
//								.collect(Collectors.toList())
//								.get(0)
//								.getRank());
//		Assertions
//				.assertEquals(
//						2,
//						rp
//								.getContributions()
//								.stream()
//								.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0002-0940-893xtrue")))
//								.collect(Collectors.toList())
//								.get(0)
//								.getRank());
//		Assertions
//				.assertEquals(
//						3,
//						rp
//								.getContributions()
//								.stream()
//								.filter(c -> c.getPerson().equals(Utils.getIdentifier(Prefixes.PERSON, "0000-0001-5291-577xtrue")))
//								.collect(Collectors.toList())
//								.get(0)
//								.getRank());
//		Assertions
//				.assertEquals(
//						4,
//						rp
//								.getContributions()
//								.stream()
//								.filter(
//										c -> c
//												.getPerson()
//												.equals(
//														Utils
//																.getIdentifier(
//																		Prefixes.TEMPORARY_PERSON,
//																		"50|doi_dedup___::0000661be7c602727bae9690778b16514")))
//								.collect(Collectors.toList())
//								.get(0)
//								.getRank());
//		researchProductDataset.show(10, 100, true);
//
//		// check manifestation 1
//		Assertions.assertEquals(3, rp.getManifestations().size());
//		Manifestation manifestation = rp
//				.getManifestations()
//				.stream()
//				.filter(
//						m -> m
//								.getHosting_datasource()
//								.equals(
//										Utils.getIdentifier(Prefixes.DATASOURCE, "10|doajarticles::6107489403b31fc7cf37cb7fda35f7f1")))
//				.collect(Collectors.toList())
//				.get(0);
//		Assertions.assertEquals("Article", manifestation.getProduct_local_type());
//		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
//		Assertions.assertEquals(1, manifestation.getDates().size());
//		Assertions.assertEquals("2021-07-29", manifestation.getDates().get(0).getValue());
//		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
//		Assertions.assertEquals(PeerReview.PEER_REVIEWED.label, manifestation.getPeer_review());
//		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
//		Assertions.assertEquals(AccessRight.CLOSED.label, manifestation.getAccess_right());
//		Assertions.assertEquals("Springer Nature TDM", manifestation.getLicence());
//		Assertions.assertEquals("https://doi.org/10.1007/s40199-021-00403-x", manifestation.getUrl());
//		Assertions.assertEquals("10.1007/s40199-021-00403-x", manifestation.getPid());
//		Assertions.assertTrue(manifestation.getBiblio() != null);
//		Biblio biblio = manifestation.getBiblio();
//		Assertions.assertTrue(biblio.getEdition() == null);
//		Assertions.assertTrue(biblio.getIssue() == null);
//		Assertions.assertEquals("Springer Science and Business Media LLC", biblio.getPublisher());
//		Assertions.assertEquals("29", biblio.getVolume());
//		Assertions.assertEquals("415", biblio.getStart_page());
//		Assertions.assertEquals("438", biblio.getEnd_page());
//
//		// check manifestation 2
//		manifestation = rp
//				.getManifestations()
//				.stream()
//				.filter(
//						m -> m
//								.getHosting_datasource()
//								.equals(
//										Utils.getIdentifier(Prefixes.DATASOURCE, "10|openaire____::55045bd2a65019fd8e6741a755395c8c")))
//				.collect(Collectors.toList())
//				.get(0);
//		Assertions.assertEquals("Article", manifestation.getProduct_local_type());
//		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
//		Assertions.assertEquals(1, manifestation.getDates().size());
//		Assertions.assertEquals("2020-01-03", manifestation.getDates().get(0).getValue());
//		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
//		Assertions.assertEquals(PeerReview.NON_PEER_REVIEWED.label, manifestation.getPeer_review());
//		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
//		Assertions.assertEquals(AccessRight.UNAVAILABLE.label, manifestation.getAccess_right());
//		Assertions.assertEquals(null, manifestation.getLicence());
//		Assertions.assertEquals("https://pubmed.ncbi.nlm.nih.gov/34327650", manifestation.getUrl());
//		Assertions.assertEquals("34327650", manifestation.getPid());
//		Assertions.assertTrue(manifestation.getBiblio() == null);
//
//		// check manifestation 3
//		manifestation = rp
//				.getManifestations()
//				.stream()
//				.filter(
//						m -> m
//								.getHosting_datasource()
//								.equals(
//										Utils.getIdentifier(Prefixes.DATASOURCE, "10|opendoar____::8b6dd7db9af49e67306feb59a8bdc52c")))
//				.collect(Collectors.toList())
//				.get(0);
//		Assertions.assertEquals("Other literature type", manifestation.getProduct_local_type());
//		Assertions.assertEquals("dnet:publication_resource", manifestation.getProduct_local_type_schema());
//		Assertions.assertEquals(1, manifestation.getDates().size());
//		Assertions.assertEquals("2021-07-29", manifestation.getDates().get(0).getValue());
//		Assertions.assertEquals("publishing", manifestation.getDates().get(0).getType());
//		Assertions.assertEquals(PeerReview.NON_PEER_REVIEWED.label, manifestation.getPeer_review());
//		Assertions.assertEquals("unavailable", manifestation.getMetadata_curation());
//		Assertions.assertEquals(AccessRight.OPEN.label, manifestation.getAccess_right());
//		Assertions.assertEquals(null, manifestation.getLicence());
//		Assertions.assertEquals("https://europepmc.org/articles/PMC8602609/", manifestation.getUrl());
//		Assertions.assertEquals("PMC8602609", manifestation.getPid());
//		Assertions.assertTrue(manifestation.getBiblio() == null);
//
//		// check relevant organization
//		Assertions.assertEquals(1, rp.getRelevant_organizations().size());
//		Assertions
//				.assertEquals(
//						Prefixes.ORGANIZATION.label + "601e510b1fda7cc6cb03329531502171",
//						rp.getRelevant_organizations().get(0));
//
//		// check funding
//		Assertions.assertEquals(1, rp.getFunding().size());
//		Assertions.assertEquals(Prefixes.GRANT.label + "a7795022763d413f5de59036ebbd0c52", rp.getFunding().get(0));
//
//		// check related products
//		Assertions.assertEquals(5, rp.getRelated_products().size());
//		Assertions
//				.assertEquals(
//						4,
//						rp
//								.getRelated_products()
//								.stream()
//								.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.CITATION.label))
//								.collect(Collectors.toList())
//								.get(0)
//								.getProduct_list()
//								.size());
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getRelated_products()
//								.stream()
//								.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.DOCUMENTS.label))
//								.collect(Collectors.toList())
//								.get(0)
//								.getProduct_list()
//								.size());
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getRelated_products()
//								.stream()
//								.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.PART.label))
//								.collect(Collectors.toList())
//								.get(0)
//								.getProduct_list()
//								.size());
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getRelated_products()
//								.stream()
//								.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.SUPPLEMENT.label))
//								.collect(Collectors.toList())
//								.get(0)
//								.getProduct_list()
//								.size());
//		Assertions
//				.assertEquals(
//						1,
//						rp
//								.getRelated_products()
//								.stream()
//								.filter(r -> r.getRelation_type().equalsIgnoreCase(RelationType.VERSION.label))
//								.collect(Collectors.toList())
//								.get(0)
//								.getProduct_list()
//								.size());

	}

	@Test
	public void testSelectRelation() throws Exception {
		final String sourcePath = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/graphForAPIExample/")
			.getPath();

		final String workingDir = getClass()
			.getResource("/eu/dnetlib/dhp/oa/graph/dump/skgif/workingDirApiExample/")
			.getPath();

		SelectRelation
			.main(
				new String[] {
					"-isSparkSessionManaged", Boolean.FALSE.toString(),
					"-sourcePath", sourcePath,
					"-workingDir", workingDir,
					"-outputPath", workingDir

				});

//		final JavaSparkContext sc = JavaSparkContext.fromSparkContext(spark.sparkContext());
//
//		JavaRDD<ResearchProduct> researchProduct = sc
//				.textFile(workingDir.toString() + "ResearchProduct")
//				.map(item -> OBJECT_MAPPER.readValue(item, ResearchProduct.class));
//
//		researchProduct.foreach(r -> System.out.println(OBJECT_MAPPER.writeValueAsString(r)));}
	}
}
