package klabbristol.holidayservice;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import klabbristol.holidayservice.dao.HolidayRepo;
import klabbristol.holidayservice.model.Holiday;
import klabbristol.holidayservice.model.NewHoliday;
import org.skife.jdbi.v2.DBI;
import ratpack.server.RatpackServer;
import ratpack.server.ServerConfig;

import java.util.List;
import java.util.Optional;

import static ratpack.jackson.Jackson.fromJson;
import static ratpack.jackson.Jackson.json;

public class Main {
    public static void main(String[] args) throws Exception {

        Config config = ConfigFactory.load();

        DBI dbi = new DBI(config.getString("databaseUrl"));
        HolidayRepo repo = dbi.onDemand(HolidayRepo.class);

        JwtParser jwtParser = Jwts.parser().setSigningKey(config.getString("secret").getBytes());

        RatpackServer.start(server -> server
            .serverConfig(ServerConfig.embedded().port(config.getInt("port")))
            .registryOf(r -> r.add(
                new ObjectMapper()
                    .registerModule(new JavaTimeModule())
                    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            ))
            .handlers(chain -> chain
                .all(ctx -> {
                    try {
                        jwtParser.parse(ctx.getRequest().getHeaders().get("Authorization"));
                        ctx.next();
                    } catch (Exception e) {
                        ctx.getResponse().status(403).send();
                    }
                })
                .path("holidays", ctx -> ctx
                    .byMethod(m -> m
                        .post(() -> {
                            ctx.parse(fromJson(NewHoliday.class))
                                .then(holiday -> {
                                    repo.add(holiday);
                                    ctx.getResponse().status(201).send();
                                });
                        })
                        .get(() -> {
                            List<Holiday> holidays =
                                Optional.ofNullable(ctx.getRequest().getQueryParams().get("user"))
                                    .map(repo::findByUser)
                                    .orElse(repo.findAll());

                            ctx.render(json(holidays));
                        })
                    )
                )
            )
        );
    }
}

@@ -878,228 +878,8 @@
 );%0A%0A
-        DBI dbi = new DBI(config.getString(%22databaseUrl%22));%0A        HolidayRepo repo = dbi.onDemand(HolidayRepo.class);%0A%0A        JwtParser jwtParser = Jwts.parser().setSigningKey(config.getString(%22secret%22).getBytes());%0A%0A
     
@@ -1028,21 +1028,16 @@
 f(r -%3E r
-.add(
 %0A       
@@ -1045,16 +1045,21 @@
         
+.add(
 new Obje
@@ -1069,16 +1069,21 @@
 apper()%0A
+     
         
@@ -1152,16 +1152,21 @@
         
+     
 .disable
@@ -1226,17 +1226,214 @@
         
+  
-)
+  )%0A                .add(new DBI(config.getString(%22databaseUrl%22)).onDemand(HolidayRepo.class))%0A                .add(Jwts.parser().setSigningKey(config.getString(%22secret%22).getBytes()))%0A            
 )%0A      
@@ -1543,17 +1543,25 @@
         
-j
+ctx.get(J
 wtParser
@@ -1561,16 +1561,23 @@
 tParser.
+class).
 parse(ct
@@ -1851,19 +1851,85 @@
  ctx -%3E 
-ctx
+%7B%0A                    HolidayRepo repo = ctx.get(HolidayRepo.class);%0A
 %0A       
@@ -1941,16 +1941,19 @@
         
+ctx
 .byMetho
@@ -2714,32 +2714,33 @@
                )
+;
 %0A               
@@ -2732,32 +2732,33 @@
                 
+%7D
 )%0A            )%0A

add repo and jwt parser to Registry