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

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

import java.io.Serializable;
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.MapFunction;
import org.apache.spark.api.java.function.MapGroupsFunction;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.dnetlib.dhp.application.ArgumentApplicationParser;
import eu.dnetlib.dhp.schema.oaf.Organization;
import eu.dnetlib.dhp.schema.oaf.Project;
import eu.dnetlib.dhp.skgif.model.Identifier;
import eu.dnetlib.dhp.skgif.model.OrganizationTypes;
import eu.dnetlib.dhp.skgif.model.Prefixes;

/**
 * @author miriam.baglioni
 * @Date 21/02/24
 */
public class DumpOrganization implements Serializable {
	private static final Logger log = LoggerFactory.getLogger(DumpOrganization.class);

	public static void main(String[] args) throws Exception {
		String jsonConfiguration = IOUtils
			.toString(
				DumpOrganization.class
					.getResourceAsStream(
						"/eu/dnetlib/dhp/oa/graph/dump/skgif/dump_organization_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 inputPath = parser.get("sourcePath");
		log.info("inputPath: {}", inputPath);

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

		SparkConf conf = new SparkConf();

		runWithSparkSession(
			conf,
			isSparkSessionManaged,
			spark -> {
				Utils.removeOutputDir(spark, outputPath + "organizations");

				mapOrganization(spark, inputPath, outputPath);
			});
	}

	private static void mapOrganization(SparkSession spark, String inputPath, String outputPath) {
		Dataset<Organization> organizations = Utils.readPath(spark, inputPath + "organization", Organization.class);
		organizations = organizations
			.filter(
				(FilterFunction<Organization>) o -> !o.getDataInfo().getDeletedbyinference()
					&& !o.getDataInfo().getInvisible())
			.groupByKey((MapFunction<Organization, String>) p -> p.getId(), Encoders.STRING())
			.mapGroups(
				(MapGroupsFunction<String, Organization, Organization>) (k, v) -> v.next(),
				Encoders.bean(Organization.class));

		organizations.map((MapFunction<Organization, eu.dnetlib.dhp.skgif.model.Organization>) o -> {
			if (!Optional.ofNullable(o.getPid()).isPresent() || o.getPid().size() == 0)
				return null;
			eu.dnetlib.dhp.skgif.model.Organization organization = new eu.dnetlib.dhp.skgif.model.Organization();
			// organization.setLocal_identifier(Utils.getIdentifier(Prefixes.ORGANIZATION, o.getId()));
			organization.setLocal_identifier(o.getId());
			organization
				.setCountry(
					Optional
						.ofNullable(o.getCountry().getClassid())
						.orElse(new String()));
			organization
				.setName(
					Optional
						.ofNullable(o.getLegalname().getValue())
						.orElse(new String()));
			organization
				.setShort_name(
					Optional
						.ofNullable(o.getLegalshortname())
						.map(v -> v.getValue())
						.orElse(new String()));
			organization
				.setIdentifiers(
					o
						.getPid()
						.stream()
						.map(p -> Identifier.newInstance(p.getQualifier().getClassid(), p.getValue()))
						.collect(Collectors.toList()));
			organization
				.setOther_names(
					o
						.getAlternativeNames()
						.stream()
						.map(a -> a.getValue())
						.collect(Collectors.toList()));
			organization.setType(getOrganizationType(o));
			return organization;
		}, Encoders.bean(eu.dnetlib.dhp.skgif.model.Organization.class))
			.filter((FilterFunction<eu.dnetlib.dhp.skgif.model.Organization>) o -> o != null)
			.write()
			.mode(SaveMode.Overwrite)
			.option("compression", "gzip")
			.json(outputPath + "organizations");
	}

	private static String getOrganizationType(Organization o) {
		if (Optional.ofNullable(o.getEcenterprise()).isPresent()
			&& o.getEcenterprise().getValue().equalsIgnoreCase("true"))
			return OrganizationTypes.COMPANY.label;
		if (Optional.ofNullable(o.getEchighereducation()).isPresent()
			&& o.getEchighereducation().getValue().equalsIgnoreCase("true"))
			return OrganizationTypes.EDUCATION.label;
		if (Optional.ofNullable(o.getEcresearchorganization()).isPresent()
			&& o.getEcresearchorganization().getValue().equalsIgnoreCase("true"))
			return OrganizationTypes.EDUCATION.label;
		if (Optional.ofNullable(o.getEcnonprofit()).isPresent()
			&& o.getEcnonprofit().getValue().equalsIgnoreCase("true"))
			return OrganizationTypes.NONPROFIT.label;

		return OrganizationTypes.OTHER.label;

	}
}
