package Web;

import com.google.gson.JsonObject;
import io.javalin.Javalin;
import io.javalin.http.UploadedFile;
import io.javalin.http.staticfiles.Location;
import lombok.Getter;
import org.eclipse.jetty.util.Loader;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class WebServer {
    final Javalin app;
    private @Getter final Path publicpath;
    private @Getter final Path exportpath;
    private @Getter final Path importpath;
    private final WebServerEvent we;
    public WebServer(WebServerEvent event){
        this.we = event;
        String userdir = System.getProperty("user.dir");
        System.out.println("User dir: "+userdir);

        exportpath = Paths.get(userdir, "export");
        importpath = Paths.get(userdir, "import");
        Path temp = Paths.get(userdir, "temp");

        createfolder(exportpath);
        createfolder(importpath);
        createfolder(temp);

        app = Javalin.create(config -> {
            config.staticFiles.add("/public");
            if (exportpath.toFile().isDirectory()){
                config.staticFiles.add(exportconfig ->{
                    exportconfig.hostedPath = "/export";
                    exportconfig.directory = exportpath.toString();
                    exportconfig.location = Location.EXTERNAL;
                });

            }
            if (importpath.toFile().isDirectory()){
                config.staticFiles.add(importconfig ->{
                    importconfig.hostedPath = "/import";
                    importconfig.directory = importpath.toString();
                    importconfig.location = Location.EXTERNAL;
                });
            }
            config.jetty.multipartConfig.cacheDirectory(temp.toString());
        });

        String resourcefolder = Loader.getResource("public").toString().replace("file:/","").replace('/', File.separatorChar);
        publicpath = Paths.get(resourcefolder);

        app.post("/import", ctx ->{
            String tablename = ctx.formParam("tablename");
            UploadedFile file = ctx.uploadedFile("file");

            JsonObject response = new JsonObject();
            if (tablename!=null && !tablename.isEmpty()){
                response.addProperty("tablename", tablename);
                if (file!=null){
                    response.addProperty("filename", file.filename());
                    System.out.println("Import request: tablename: "+tablename+", filename: "+file.filename()+", size: "+file.size());
                    try(InputStream is = file.content()){
                        Path dest = importpath.resolve(file.filename());
                        Files.copy(is,dest, StandardCopyOption.REPLACE_EXISTING);

                        if (we!=null){
                            String result = we.onImport(tablename, dest);
                            response.addProperty("result",result);
                            ctx.status("success".equals(result)?200:500).result(response.toString());
                        } else {
                            response.addProperty("result","no event handler");
                            ctx.status(500).result(response.toString());
                        }
                    } catch (Exception e){
                        response.addProperty("result","error copying file: "+e.getMessage());
                        ctx.status(500).result(response.toString());
                    }



                } else {
                    response.addProperty("result","file not provided");
                    ctx.status(400).result(response.toString());
                }
            } else {
                response.addProperty("result","tablename not provided");
                ctx.status(400).result(response.toString());
            }



        });
    }

    private void createfolder(Path path){
        if (Files.exists(path)) return;
        try {
            Files.createDirectories(path);
            System.out.println("Folder created: "+path);
        } catch (Exception e){
            System.out.println("Error creating folder: "+path+", error: "+e.getMessage());
        }

    }

    public void start(String localip, int port){
        app.start(localip, port);
    }

    public void start(int port){
        app.start(port);

    }

    public void stop(){
        app.stop();
    }
}
