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

import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;

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.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SparkSession;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
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.skgif.model.Datasource;
import eu.dnetlib.dhp.skgif.model.Grant;

/**
 * @author miriam.baglioni
 * @Date 22/02/24
 */
public class DumpGrantTest 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(DumpGrantTest.class);

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

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

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

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

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

				});

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

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

		Dataset<Grant> grantDataset = spark.createDataset(grant.rdd(), Encoders.bean(Grant.class));
		Assertions.assertEquals(12, grantDataset.count());
		grantDataset.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 testDumpGrantApi() 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();

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

				});

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

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

		grant.foreach(g -> System.out.println(OBJECT_MAPPER.writeValueAsString(g)));

	}

	@Test
	public void testDumpFunder() throws Exception {

		String fundingtree = "<fundingtree>" +
			"                        <funder>" +
			"                            <id>ec__________::EC</id>\n" +
			"                            <shortname>EC</shortname>\n" +
			"                            <name>European Commission</name>\n" +
			"                            <jurisdiction>EU</jurisdiction>\n" +
			"                        </funder>\n" +
			"                        <funding_level_2>\n" +
			"                            <id>ec__________::EC::FP7::SP2::ERC</id>\n" +
			"                            <description>ERC</description>\n" +
			"                            <name>ERC</name>\n" +
			"                            <class>ec:program</class>\n" +
			"                            <parent>\n" +
			"                                <funding_level_1>\n" +
			"                                    <id>ec__________::EC::FP7::SP2</id>\n" +
			"                                    <description>SP2-Ideas</description>\n" +
			"                                    <name>SP2</name>\n" +
			"                                    <class>ec:specificprogram</class>\n" +
			"                                    <parent>\n" +
			"                                        <funding_level_0>\n" +
			"                                            <id>ec__________::EC::FP7</id>\n" +
			"                                            <description>SEVENTH FRAMEWORK PROGRAMME</description>\n" +
			"                                            <name>FP7</name>\n" +
			"                                            <parent />\n" +
			"                                            <class>ec:frameworkprogram</class>\n" +
			"                                        </funding_level_0>\n" +
			"                                    </parent>\n" +
			"                                </funding_level_1>\n" +
			"                            </parent>\n" +
			"                        </funding_level_2>\n" +
			"                    </fundingtree>".replace("\n", " ");
		System.out.println(getFundingStream(fundingtree));

	}

	private static String getFundingStream(String fundingtree) throws DocumentException {
		final Document doc;

		doc = new SAXReader().read(new StringReader(fundingtree));
		if (Optional.ofNullable(doc.selectNodes("//funding_level_0")).isPresent() &&
			doc.selectNodes("//funding_level_0").size() > 0 &&
			Optional.ofNullable(doc.selectNodes("//funding_level_0/name")).isPresent() &&
			doc.selectNodes("//funding_level_0/name").size() > 0)
			return ((org.dom4j.Node) (doc.selectNodes("//funding_level_0/name").get(0))).getText();
		return new String();

	}
}
