package com.r11.tools.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.r11.tools.controller.internal.GlobalControllerManifest;
import com.r11.tools.controller.internal.HandlerType;
import com.r11.tools.controller.internal.RestController;
import com.r11.tools.controller.internal.ScopedControllerManifest;
import spark.Request;
import spark.Response;

@GlobalControllerManifest(path = "/json")
public class JsonController implements RestController {

    private final Gson prettyGson = new GsonBuilder()
            .disableHtmlEscaping()
            .setPrettyPrinting()
            .create();

    private final Gson gson = new GsonBuilder()
            .disableHtmlEscaping()
            .create();

    @ScopedControllerManifest(method = HandlerType.POST, path = "/formatting")
    public void formatting(Request request, Response response) {
        long startProcess = System.currentTimeMillis();
        JsonObject responseJson = new JsonObject();

        try {
            JsonObject requestJson = this.gson.fromJson(request.body(), JsonObject.class);

            response.status(200);

            responseJson.addProperty("data", this.prettyGson.toJson(requestJson));
            responseJson.addProperty("time", System.currentTimeMillis() - startProcess);

            response.body(this.prettyGson.toJson(responseJson));
        } catch (Exception e) {
            Throwable cause = e.getCause();

            response.status(500);

            responseJson.addProperty("data", cause == null ? e.getMessage() : cause.getMessage());
            responseJson.addProperty("time", System.currentTimeMillis() - startProcess);

            response.body(this.prettyGson.toJson(responseJson));
        }
    }

    @ScopedControllerManifest(method = HandlerType.POST, path = "/minimize")
    public void minimize(Request request, Response response) {
        long startProcess = System.currentTimeMillis();
        JsonObject responseJson = new JsonObject();

        try {
            JsonObject requestJson = this.prettyGson.fromJson(request.body(), JsonObject.class);

            response.status(200);

            responseJson.addProperty("data", this.gson.toJson(requestJson));
            responseJson.addProperty("time", System.currentTimeMillis() - startProcess);

            response.body(this.gson.toJson(responseJson));
        } catch (Exception e) {
            Throwable cause = e.getCause();

            response.status(500);

            responseJson.addProperty("data", cause == null ? e.getMessage() : cause.getMessage());
            responseJson.addProperty("time", System.currentTimeMillis() - startProcess);

            response.body(this.prettyGson.toJson(responseJson));
        }
    }
}
