package me.tomassetti;
 
import com.beust.jcommander.JCommander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.Data;
import me.tomassetti.model.Model;
import me.tomassetti.sql2omodel.Sql2oModel;
import org.sql2o.Sql2o;
import org.sql2o.converters.UUIDConverter;
import org.sql2o.quirks.PostgresQuirks;

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;

import static spark.Spark.get;
import static spark.Spark.post;
import static spark.SparkBase.port;

public class BlogService 
{

    private static final Logger logger = Logger.getLogger(BlogService.class.getCanonicalName());

    private static final int HTTP_BAD_REQUEST = 400;

    @Data
    static class NewPostPayload {
        private String title;
        private List<String> categories = new LinkedList<>();
        private String content;

        public boolean isValid() {
            return title != null && !title.isEmpty() && content != null && !content.isEmpty();
        }
    }

    @Data
    static class NewCommentPayload {
        private String author;
        private String content;

        public boolean isValid() {
            return author != null && !author.isEmpty() && content != null && !content.isEmpty();
        }
    }
    
    public static String dataToJson(Object data) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            StringWriter sw = new StringWriter();
            mapper.writeValue(sw, data);
            return sw.toString();
        } catch (IOException e){
            throw new RuntimeException("IOException from a StringWriter?");
        }
    }
    
    public static void main( String[] args) {
        CommandLineOptions options = new CommandLineOptions();
        new JCommander(options, args);

        logger.finest("Options.debug = " + options.debug);
        logger.finest("Options.database = " + options.database);
        logger.finest("Options.dbHost = " + options.dbHost);
        logger.finest("Options.dbUsername = " + options.dbUsername);
        logger.finest("Options.dbPort = " + options.dbPort);
        logger.finest("Options.servicePort = " + options.servicePort);

        port(options.servicePort);

        Sql2o sql2o = new Sql2o("jdbc:postgresql://" + options.dbHost + ":" + options.dbPort + "/" + options.database,
                options.dbUsername, options.dbPassword, new PostgresQuirks() {
            {
                // make sure we use default UUID converter.
                converters.put(UUID.class, new UUIDConverter());
            }
        });

        Model model = new Sql2oModel(sql2o);

        // insert a post (using HTTP post method)
        post("/posts", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            NewPostPayload creation = mapper.readValue(request.body(), NewPostPayload.class);
            if (!creation.isValid()) {
                response.status(HTTP_BAD_REQUEST);
                return "";
            }
            UUID id = model.createPost(creation.getTitle(), creation.getContent(), creation.getCategories());
            response.status(200);
            response.type("application/json");
            return id;
        });

        // get all post (using HTTP get method)
        get("/posts", (request, response) -> {
            response.status(200);
            response.type("application/json");
            return dataToJson(model.getAllPosts());
        });

        post("/posts/:uuid/comments", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            NewCommentPayload creation = mapper.readValue(request.body(), NewCommentPayload.class);
            if (!creation.isValid()) {
                response.status(HTTP_BAD_REQUEST);
                return "";
            }
            UUID post = UUID.fromString(request.params(":uuid"));
            if (!model.existPost(post)){
                response.status(400);
                return "";
            }
            UUID id = model.createComment(post, creation.getAuthor(), creation.getContent());
            response.status(200);
            response.type("application/json");
            return id;
        });

        get("/posts/:uuid/comments", (request, response) -> {
            UUID post = UUID.fromString(request.params(":uuid"));
            if (!model.existPost(post)) {
                response.status(400);
                return "";
            }
            response.status(200);
            response.type("application/json");
            return dataToJson(model.getAllCommentsOn(post));
        });
    }
}

@@ -374,16 +374,38 @@
 sQuirks;
+%0Aimport spark.Request;
 %0A%0Aimport
@@ -1849,36 +1849,198 @@
         %7D%0A    %7D%0A
+%0A
     
+private static boolean shouldReturnHtml(Request request) %7B%0A        Object accept = request.attribute(%22Accept%22);%0A        return %22text/html%22.equals(accept);%0A    %7D%0A
 %0A    public stat
@@ -3717,38 +3717,250 @@
         
-response.status(200);%0A
+if (shouldReturnHtml(request)) %7B%0A                response.status(200);%0A                response.type(%22text/html%22);%0A                return dataToJson(model.getAllPosts());%0A            %7D else %7B%0A                response.status(200);%0A    
         
@@ -3990,32 +3990,36 @@
 ication/json%22);%0A
+    
             retu
@@ -4046,32 +4046,46 @@
 getAllPosts());%0A
+            %7D%0A
         %7D);%0A%0A   

add shouldReturnHtml