
package eu.dnetlib.dhp.ircdl_extention;

import static eu.dnetlib.dhp.common.SparkSessionSupport.runWithSparkHiveSession;

import java.util.Optional;

import org.apache.commons.io.IOUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.SparkSession;

import eu.dnetlib.dhp.application.ArgumentApplicationParser;
import eu.dnetlib.dhp.ircdl_extention.model.Result;

public class PrepareDataciteSpark {

	public static void main(String[] args) throws Exception {

		String jsonConfiguration = IOUtils
			.toString(
				PrepareDataciteSpark.class
					.getResourceAsStream(
						"/eu/dnetlib/dhp/ircdl_extention/prepare_parameters.json"));

		final ArgumentApplicationParser parser = new ArgumentApplicationParser(jsonConfiguration);

		parser.parseArgument(args);

		Boolean isSparkSessionManaged = Optional
			.ofNullable(parser.get("isSparkSessionManaged"))
			.map(Boolean::valueOf)
			.orElse(Boolean.TRUE);

		final String inputPath = parser.get("inputPath");

		final String outputPath = parser.get("outputPath");

		SparkConf conf = new SparkConf();
		conf.set("hive.metastore.uris", "thrift://iis-cdh5-test-m3.ocean.icm.edu.pl:9083");

		runWithSparkHiveSession(
			conf,
			isSparkSessionManaged,
			spark -> {
				Utils.removeOutputDir(spark, outputPath);
				exec(spark, outputPath, inputPath);
			});
	}

	private static void exec(SparkSession spark, String output_path, String input_path) {

		Dataset<Result> datacite = Utils
			.readPath(
				spark, input_path, Result.class)
			.filter(
				(FilterFunction<Result>) r -> r.getId().startsWith("50|datacite"));

		datacite.write().option("compression", "gzip").mode(SaveMode.Overwrite).json(output_path + "allDatacite");
		getProviderResult(output_path, datacite, "Zenodo");
		getProviderResult(output_path, datacite, "Figshare");
		getProviderResult(output_path, datacite, "Dryad");

	}

	private static void getProviderResult(String output_path, Dataset<Result> datacite, String provider) {
		datacite
			.filter(
				(FilterFunction<Result>) r -> r
					.getPid()
					.stream()
					.anyMatch(p -> p.getKey().equals("doi") && p.getValue().contains(provider.toLowerCase())))
			.write()
			.option("compression", "gzip")
			.mode(SaveMode.Overwrite)
			.json(output_path + provider);
	}

}
