
package eu.dnetlib.dhp;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.github.imifou.jsonschema.module.addon.AddonModule;
import com.github.victools.jsonschema.generator.*;

import eu.dnetlib.dhp.oa.model.community.CommunityResult;
import eu.dnetlib.dhp.oa.model.graph.*;

public class ExecCreateSchemas {
	final static String DIRECTORY = "/eu/dnetlib/dhp/schema/dump/jsonschemas/";
	SchemaGenerator generator;

	private void init() {

		AddonModule module = new AddonModule();
		SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(
			new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT),
			SchemaVersion.DRAFT_7,
			OptionPreset.PLAIN_JSON)
				.with(module)
				.with(Option.SCHEMA_VERSION_INDICATOR)
				.without(Option.NONPUBLIC_NONSTATIC_FIELDS_WITHOUT_GETTERS);
		SchemaGeneratorConfig config = configBuilder.build();
		generator = new SchemaGenerator(config);
	}

	private void generate(Type targetType, String directory, String filename) throws IOException {
		JsonNode jsonSchema = generator.generateSchema(targetType);

		String dir = Paths
			.get(Paths.get(getClass().getResource("/").getPath()).toAbsolutePath() + directory)
			.toString();

		System.out.println(dir);
		if (!Files.exists(Paths.get(dir))) {
			Files.createDirectories(Paths.get(dir));
		}

		if (!Files.exists(Paths.get(dir + "/" + filename))) {
			Files.createFile(Paths.get(dir + "/" + filename));
		}

		File f = new File(dir + "/" + filename);

		try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(f)))) {
			writer.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
		}

	}

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

		ExecCreateSchemas ecs = new ExecCreateSchemas();
		ecs.init();
		ecs.generate(GraphResult.class, DIRECTORY, "result_schema.json");
		ecs.generate(ResearchCommunity.class, DIRECTORY, "community_infrastructure_schema.json");
		ecs.generate(Datasource.class, DIRECTORY, "datasource_schema.json");
		ecs.generate(Project.class, DIRECTORY, "project_schema.json");
		ecs.generate(Relation.class, DIRECTORY, "relation_schema.json");
		ecs.generate(Organization.class, DIRECTORY, "organization_schema.json");

		ecs.generate(CommunityResult.class, DIRECTORY, "community_result_schema.json");

	}
}
