
package eu.dnetlib.dhp.ircdl_extention;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
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.Author;
import eu.dnetlib.dhp.ircdl_extention.model.KeyValue;
import eu.dnetlib.dhp.ircdl_extention.model.Result;
import eu.dnetlib.dhp.schema.common.ModelConstants;

public class SelectAuthorWithOrcidOnlySpark {

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

		String jsonConfiguration = IOUtils
			.toString(
				PrepareResultSpark.class
					.getResourceAsStream(
						"/eu/dnetlib/dhp/ircdl_extention/prepare_result_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();

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

	private static void selectAuthors(SparkSession spark, String input_path, String output_path) {
		Dataset<Author> resultDataset = Utils.readPath(spark, input_path, Author.class);
		resultDataset.flatMap((FlatMapFunction<Author, Result>) p -> {
			List<Result> reslist = new ArrayList<>();
			p.getApid().forEach(a -> {
				if (a.getKey().equals(ModelConstants.ORCID_PENDING) || a.getKey().equals(ModelConstants.ORCID)) {
					Result r = Result.fromAuthor(p);
					r.setOid(a.getValue());
					reslist.add(r);
				}
			});
			return reslist.iterator();
		}, Encoders.bean(Result.class))
			.write()
			.option("compressio", "gzip")
			.mode(SaveMode.Overwrite)
			.json(output_path);
	}
}
