package com.r11.tools;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.r11.tools.controller.JsonController;
import com.r11.tools.controller.ProcessorInfoController;
import com.r11.tools.controller.XPathController;
import com.r11.tools.controller.XsdController;
import com.r11.tools.controller.XsltController;
import com.r11.tools.controller.internal.RestControllerRegistry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import spark.Spark;

public class SparkApplication {

    public static void run() {
        // TODO: read port from config
        Spark.port(8081);

        Spark.after((request, response) -> {
            response.header("Access-Control-Allow-Origin", "*");
            response.header("access-control-allow-headers", "*");
            response.header("access-control-expose-headers", "*");
            response.header("Access-Control-Allow-Methods", "POST");
        });

        Logger logger = LogManager.getLogger(SparkApplication.class);

        Gson gson = new GsonBuilder()
            .disableHtmlEscaping()
            .setPrettyPrinting()
            .create();

        Gson jsongson = new GsonBuilder()
            .disableHtmlEscaping()
            .create();

        RestControllerRegistry registry = new RestControllerRegistry();
        registry.registerController(new ProcessorInfoController(logger));
        registry.registerController(new XsdController(gson, logger));
        registry.registerController(new XPathController(gson, logger));
        registry.registerController(new XsltController(gson, logger));
        registry.registerController(new JsonController(gson, jsongson, logger));

        registry.register();

        logger.info("Server is online at port: " + Spark.port());
    }
}
