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

import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;

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.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SparkSession;
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.RelationPerProduct;
import eu.dnetlib.dhp.skgif.model.Organization;
import eu.dnetlib.dhp.skgif.model.Prefixes;
import eu.dnetlib.dhp.skgif.model.ResearchProduct;

/**
 * @author miriam.baglioni
 * @Date 22/02/24
 */
public class DumpOrganizationTest implements Serializable {
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	private static SparkSession spark;

	private static Path workingDir;

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

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

		SparkConf conf = new SparkConf();
		conf.setAppName(DumpOrganizationTest.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(DumpOrganizationTest.class.getSimpleName())
			.config(conf)
			.getOrCreate();
	}

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

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

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

				});

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

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

		Dataset<Organization> organizationDataset = spark
			.createDataset(organization.rdd(), Encoders.bean(Organization.class));
		Assertions.assertEquals(34 - 19, organizationDataset.count());
		organizationDataset.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().stream().filter(rp -> rp.getRelation_type().equalsIgnoreCase("issupplementedby")).count());
//        Assertions.assertEquals(1, temp.getRelatedProduct().stream().filter(rp -> rp.getRelation_type().equalsIgnoreCase("isdocumentedby")).count());
//
//        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);
//
//

	}

	@Test
	public void testDumpOrganizationAPI() 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();

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

				});

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

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

		organization.foreach(o -> System.out.println(OBJECT_MAPPER.writeValueAsString(o)));

	}
}
