package org.dominokit.domino.api.server.plugins;

import com.google.auto.service.AutoService;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import org.dominokit.domino.api.server.DominoLoaderPlugin;
import org.dominokit.domino.api.server.PluginContext;

import java.nio.file.Paths;

import static java.util.Objects.nonNull;

@AutoService(DominoLoaderPlugin.class)
public class StaticResourcesConfiguratorPlugin extends BaseDominoLoaderPlugin {

    @Override
    public void applyPlugin(CompleteHandler completeHandler) {
        StaticHandler staticHandler = StaticHandler.create();
        if (nonNull(System.getProperty("domino.webroot.location"))) {
            staticHandler.setAllowRootFileSystemAccess(true);
            staticHandler.setWebRoot(systemWebRoot());
        } else {
            staticHandler.setWebRoot(context.getWebRoot());
        }

        context.getRouter().route("/").order(Integer.MAX_VALUE - 3)
                .handler(this::serveIndexPage);

        context.getRouter().route("/static/*").order(Integer.MAX_VALUE - 2)
                .handler(staticHandler)
                .failureHandler(this::serveResource);

        context.getRouter().route("/*").order(Integer.MAX_VALUE)
                .handler(this::serveResource);

        completeHandler.onCompleted();
    }

    private String systemWebRoot() {
        return Paths.get(System.getProperty("domino.webroot.location")).toAbsolutePath().toString();
    }

    private HttpServerResponse serveIndexPage(RoutingContext event) {
        return event.response().putHeader("Content-type", "text/html")
                .sendFile( context.getWebRoot()+ "/index.html");
    }

    private void serveResource(RoutingContext routingContext) {
        routingContext.response()
                .sendFile( context.getWebRoot() + routingContext.request().path().replace("/static", ""), event -> {
                    if (event.failed())
                        serveIndexPage(routingContext);
                });
    }

    @Override
    public int order() {
        return PluginContext.STATIC_RESOURCES_ORDER;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

@@ -1690,33 +1690,32 @@
       .sendFile(
- 
 context.getWebRo
@@ -1718,16 +1718,17 @@
 ebRoot()
+ 
 + %22/inde
@@ -1816,16 +1816,21 @@
         
+if (!
 routingC
@@ -1846,17 +1846,70 @@
 sponse()
+.ended()) %7B
 %0A
+            routingContext.response()%0A    
         
@@ -1926,17 +1926,16 @@
 endFile(
- 
 context.
@@ -2032,24 +2032,28 @@
             
+  
+  
 if (event.fa
@@ -2060,16 +2060,20 @@
 iled())%0A
+    
         
@@ -2140,11 +2140,25 @@
     
-%7D);
+    %7D);%0A        %7D
 %0A   

add condition for serve resource file only if the response is not ended