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

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

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.api.java.function.MapFunction;
import org.apache.spark.sql.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.dnetlib.dhp.application.ArgumentApplicationParser;
import eu.dnetlib.dhp.schema.common.ModelSupport;
import eu.dnetlib.dhp.schema.oaf.Relation;
import eu.dnetlib.dhp.schema.oaf.Result;
import scala.Tuple2;

/**
 * @author miriam.baglioni
 * @Date 22/09/23
 */
public class SparkCopyGraph implements Serializable {

	private static final Logger log = LoggerFactory.getLogger(SparkCopyGraph.class);

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

		String jsonConfiguration = IOUtils
			.toString(
				SparkCopyGraph.class
					.getResourceAsStream(
						"/eu/dnetlib/dhp/oa/graph/dump/copygraph_parameters.json"));

		final ArgumentApplicationParser parser = new ArgumentApplicationParser(jsonConfiguration);

		parser.parseArgument(args);

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

		log.info("isSparkSessionManaged: {}", isSparkSessionManaged);

		final String hivePath = parser.get("hivePath");
		log.info("hivePath: {}", hivePath);

		final String outputPath = parser.get("outputPath");
		log.info("outputPath: {}", outputPath);

		SparkConf conf = new SparkConf();

		runWithSparkSession(
			conf,
			isSparkSessionManaged,
			spark ->

			execCopy(
				spark,
				hivePath,
				outputPath));
	}

	private static void execCopy(SparkSession spark, String hivePath, String outputPath) {

		ModelSupport.oafTypes.entrySet().parallelStream().forEach(entry -> {
			String entityType = entry.getKey();
			Class<?> clazz = entry.getValue();
			// if (!entityType.equalsIgnoreCase("relation")) {
			spark
				.read()
				.schema(Encoders.bean(clazz).schema())
				.parquet(hivePath + "/" + entityType)
				.write()
				.mode(SaveMode.Overwrite)
				.option("compression", "gzip")
				.json(outputPath + "/" + entityType);

		});

	}

}
