package eu.mhsl.minenet.minigames.api;

import com.google.gson.Gson;
import spark.Request;
import spark.Response;
import spark.Route;

import java.lang.reflect.ParameterizedType;

public abstract class Controller<Q, R> implements Route {
    private final Class<Q> requestType;

    @SuppressWarnings("unchecked")
    public Controller() {
        this.requestType = ((Class<Q>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
    }

    @Override
    public Object handle(Request request, Response response) throws Exception {
        response.header("Access-Control-Allow-Origin", "*");
        response.header("Access-Control-Allow-Methods", "*");

        Q req;

        if(request.body().isEmpty()) {
            req = null;
        } else {
            req = new Gson().fromJson(request.body(), this.requestType);
        }

        return new Gson().toJson(handle(req, response));
    }

    public abstract R handle(Q request, Response response);
}
