package fr.imta.addressbook.server;

import fr.imta.addressbook.model.Database;
import fr.imta.addressbook.server.handlers.AddressBookHandler;
import fr.imta.addressbook.server.handlers.PersonHandler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;

public class VertxServer {
    private Vertx vertx;
    private Database db;

    public VertxServer() {
        this.vertx = Vertx.vertx();
        
        this.db = new Database();
    }

    public void start() {
        Router router = Router.router(vertx);

        // add handlers for payload parsing and to allow swagger to send requests
        router.route().handler(BodyHandler.create());
        router.route().handler(CorsHandler.create().addOrigin("*").allowedMethod(HttpMethod.DELETE).allowedMethod(HttpMethod.PUT));

        // create handlers and registers routes
        PersonHandler ph = new PersonHandler(db);
        router.get("/api/person").handler(ph::getIds);
        router.post("/api/person").handler(ph::create);
        router.delete("/api/person/:id").handler(ph::delete);
        router.put("/api/person/:id").handler(ph::update);
        router.get("/api/person/:id").handler(ph::getById);

        // create handlers and registers routes
        AddressBookHandler ah = new AddressBookHandler(db);
        
        // write the remaining routes for agenda


        router.get("/").handler(StaticHandler.create("./static"));
        router.get("/static/*").handler(StaticHandler.create("./static"));

        // start the server and check for errors
        vertx.createHttpServer().requestHandler(router).listen(8080)
            .onSuccess(e -> 
                System.out.println("Server is listening on localhost:" + e.actualPort())
            ).onFailure(e -> {
                System.out.println("Cannot start server, got error: " + e.getLocalizedMessage());
                System.exit(1);
            });
    }

    public static void main(String[] args) {
        new VertxServer().start();
    }
}
