
package eu.dnetlib.dhp.ircdl_extention;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
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.api.java.function.FlatMapGroupsFunction;
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 com.fasterxml.jackson.core.JsonProcessingException;

import eu.dnetlib.dhp.application.ArgumentApplicationParser;
import eu.dnetlib.dhp.ircdl_extention.model.Author;
import eu.dnetlib.dhp.ircdl_extention.model.Orcid;
import eu.dnetlib.dhp.ircdl_extention.model.Result;
import eu.dnetlib.dhp.ircdl_extention.model.ShuffleInfo;
import scala.Tuple2;

public class WrongSpark {
	/**
	 * takes as input the orcid normalized and the entry normalized to be checked against orcid
	 * returns the lower bound of wrong attribution
	 */

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

		String jsonConfiguration = IOUtils
			.toString(
				WrongSpark.class
					.getResourceAsStream(
						"/eu/dnetlib/dhp/ircdl_extention/wrong_orcid_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 orcidPath = parser.get("orcidPath");

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

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

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

		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);
				findWrong(spark, orcidPath, outputPath + "/wrong", resultPath);
				findShuffle(spark, orcidPath, outputPath + "/shuffle", resultPath, authorPath);
			});
	}

	private static void findShuffle(SparkSession spark, String orcidPath, String outputPath, String resultPath,
		String authorPath) {

		Utils
			.readPath(spark, authorPath, Author.class)
			.map(
				(MapFunction<Author, ShuffleInfo>) r -> ShuffleInfo
					.newInstance(r.getName(), r.getSurname(), r.getFullname(), r.getId()),
				Encoders.bean(ShuffleInfo.class))
			.union(
				getWrong(spark, orcidPath, resultPath)
					.map((MapFunction<Tuple2<Result, Orcid>, ShuffleInfo>) t2 ->

					ShuffleInfo
						.newInstance(
							t2._1().getName(), t2._1().getSurname(), t2._1().getFullname(),
							t2._1().getId(), t2._2().getName(), t2._2().getSurname(),
							t2._2().getCreditname(), t2._2().getOtherNames(), t2._2().getOrcid()),
						Encoders.bean(ShuffleInfo.class)))
			.groupByKey((MapFunction<ShuffleInfo, String>) si -> si.getId(), Encoders.STRING())
			.flatMapGroups((FlatMapGroupsFunction<String, ShuffleInfo, ShuffleInfo>) (s, it) -> {
				List<ShuffleInfo> shuffleInfoList = new ArrayList();
				List<ShuffleInfo> ret = new ArrayList<>();
				shuffleInfoList.add(it.next());
				it.forEachRemaining(e -> shuffleInfoList.add(e));
				shuffleInfoList
					.stream()
					.filter(e -> Optional.ofNullable(e.getOrcid()).isPresent())
					.forEach(e -> {
						if (checkShuffle(e, shuffleInfoList))
							ret.add(e);
					});
				return ret.iterator();
			}, Encoders.bean(ShuffleInfo.class))
			.filter(Objects::nonNull)
			.write()
			.option("compression", "gzip")
			.mode(SaveMode.Overwrite)
			.json(outputPath);

		/*
		 * def checkShuffle(x): alis = [a for a in x[1]] dic = {} count = 0 for entry in alis: if entry['orcid'] != '':
		 * dic[entry['orcid']] = entry for orcid in dic: name = dic[orcid]['oname'] surname = dic[orcid]['osurname'] for
		 * author in alis: if author['aname'] == "" or author['asurname'] == "": if checkContains([author['afullname']],
		 * addInListAll([], name + " " + surname)): count += 1 break else: if checkContains([author['aname'] + " " +
		 * author['asurname']], addInListAll([], name + " " + surname)): count += 1 break return count
		 */
		// candidate_shuffle = zenodo_normalized.map(lambda x: (x['id'], {'aname':x['name'], 'asurname': x['surname'],
		// 'afullname': x['fullname'], 'oname':"", 'osurname':"", 'orcid':''})). union (
		// join_orcid_filtered.map(lambda e: (e['id'], {'aname':e['nameg'], 'asurname':e['surnameg'],
		// 'afullname':e['fullnameg'], 'oname':e['name'],
		// 'osurname':e['surname'],'orcid':e['orcid']}))).groupByKey().filter(toBeChecked)
	}

	private static boolean checkShuffle(ShuffleInfo e, List<ShuffleInfo> shuffleInfoList) {

		boolean b = shuffleInfoList
			.stream()
			.anyMatch(
				si -> {
					try {
						return Utils
							.filterFunction(
								new Tuple2<>(Result.newInstance(si.getAfullname()),
									Orcid
										.newInstance(
											e.getOname(), e.getOsurname(), e.getOcreditName(),
											e.getoOtherNames())));
					} catch (JsonProcessingException ex) {
						throw new RuntimeException(ex);
					}
				});

		return b;
	}

	private static Dataset<Tuple2<Result, Orcid>> getWrong(SparkSession spark, String orcidPath, String resultPath) {
		Dataset<Orcid> orcidDataset = Utils
			.readPath(spark, orcidPath, Orcid.class)
			.filter((FilterFunction<Orcid>) o -> !o.getName().contains("deactivated"));
		Dataset<Result> resultDataset = Utils.readPath(spark, resultPath, Result.class);

		return resultDataset
			.joinWith(
				orcidDataset, resultDataset
					.col("oid")
					.equalTo(orcidDataset.col("orcid")),
				"inner")
			.filter((FilterFunction<Tuple2<Result, Orcid>>) t2 -> !Utils.conservativeFilterFunction(t2));
	}

	private static void findWrong(SparkSession spark, String orcidPath, String outputPath, String resultPath) {
		getWrong(spark, orcidPath, resultPath)
			.write()
			.option("compression", "gzip")
			.mode(SaveMode.Overwrite)
			.json(outputPath);

	}

}
