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 com.r11.tools.xml.Saxon;
import com.r11.tools.xml.Xalan;
import com.r11.tools.xml.XmlEngine;
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();
        XmlEngine saxon = new Saxon();
        XmlEngine xalan = new Xalan();


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

        registry.register();

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