
package eu.dnetlib.dhp.ircdl_extention;

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

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.MapFunction;
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.Orcid;

public class PrepareNormalizedOrcid {

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

		String jsonConfiguration = IOUtils
			.toString(
				PrepareNormalizedOrcid.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();

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

	private static void execNormalize(SparkSession spark, String outputPath, String inputPath) {
		Dataset<Orcid> orcid = Utils.readPath(spark, inputPath, Orcid.class);
		orcid.map((MapFunction<Orcid, Orcid>) o -> {
			o.setName(Utils.normalizeString(o.getName()));
			o.setSurname(Utils.normalizeString(o.getSurname()));
			o.setCreditname(Utils.normalizeString(o.getCreditname()));
			o
				.setOtherNames(
					o
						.getOtherNames()
						.stream()
						.map(on -> Utils.normalizeString(on))
						.collect(Collectors.toList()));
			return o;
		}, Encoders.bean(Orcid.class))
			.write()
			.option("compression", "gzip")
			.mode(SaveMode.Overwrite)
			.json(outputPath);
	}

}
