package ch.mytodo;

import ch.mytodo.api.DebugService;
import ch.mytodo.impl.PersistenceServiceImpl;
import ch.mytodo.impl.ToDoServiceImpl;
import ch.mytodo.jooq.codegen.tables.pojos.ToDo;
import ch.mytodo.jooq.codegen.tables.pojos.ToDoList;
import com.google.gson.Gson;

import java.util.List;

import static spark.Spark.*;

public class MyToDoServer {

    private DebugService debugService;
    private ToDoServiceImpl toDoService;
    private static Gson gson = new Gson();

    public MyToDoServer(){
        debugService = new DebugService();
        debugService.setPersistenceService(new PersistenceServiceImpl());
        toDoService = new ToDoServiceImpl();
        toDoService.setPersistenceService(new PersistenceServiceImpl());
    }

    public void startServer(){
        staticFiles.location("web");

        get("/todolists", (request, response) -> {
            response.type("application/json");
            response.header("Access-Control-Allow-Origin", "http://localhost:4200");
            List<ToDoList> allToDos = toDoService.getAllToDoLists();
            return gson.toJson(allToDos);
        });
        get("/todos", (request, response) -> {
            response.type("application/json");
            response.header("Access-Control-Allow-Origin", "http://localhost:4200");
            List<ToDo> allToDos = toDoService.getAllToDos();
            return gson.toJson(allToDos);
        });
        get("/ping", (req, res) -> debugService.ping());
        get("/persistence", (request, response) -> {
            response.type("application/json");
            return debugService.schemaVersionInfo();
        });
        post("/todo", (req, res) -> {
            res.header("Access-Control-Allow-Origin", "http://localhost:4200");
            ToDo todo= gson.fromJson(req.body(), ToDo.class);
            ToDo justCreatedTodo = toDoService.create(todo);
            return gson.toJson(justCreatedTodo);
        });
    }
}

@@ -287,16 +287,43 @@
 il.List;
+%0Aimport java.util.Optional;
 %0A%0Aimport
@@ -1429,32 +1429,555 @@
 s);%0A        %7D);%0A
+        get(%22/todos/:id%22, (request, response) -%3E %7B%0A            Long id = Long.valueOf(request.params(%22:id%22));%0A            response.type(%22application/json%22);%0A            response.header(%22Access-Control-Allow-Origin%22, %22http://localhost:4200%22);%0A            Optional%3CString%3E todo = toDoService.getAllToDos()%0A                    .stream()%0A                    .filter(t -%3E t.getToDoNo().equals(id))%0A                    .map(t -%3E gson.toJson(t))%0A                    .findFirst();%0A            return todo.orElse(null);%0A        %7D);%0A
         get(%22/pi

add new route url/todos/:id