package io.quarkus.undertow.websockets.deployment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

import org.jboss.logging.Logger;

import io.quarkus.deployment.devmode.HotReplacementContext;
import io.quarkus.deployment.devmode.HotReplacementSetup;
import io.quarkus.undertow.runtime.UndertowDeploymentRecorder;
import io.undertow.Handlers;
import io.undertow.predicate.Predicates;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;

public class WebsocketHotReloadSetup implements HotReplacementSetup {

    private static Logger logger = Logger.getLogger(WebsocketHotReloadSetup.class);

    static volatile String replacementPassword;

    @Override
    public void setupHotDeployment(HotReplacementContext hotReplacementContext) {
        // we can't use the typical ConfigProvider.getConfig() because the config infrastructure isn't setup at this point
        String password = System.getProperty(HotReplacementWebsocketEndpoint.QUARKUS_LIVE_RELOAD_PASSWORD);
        if (password == null || password.isEmpty()) {
            password = System.getenv(HotReplacementWebsocketEndpoint.QUARKUS_LIVE_RELOAD_PASSWORD_ENV);
        }

        if (password != null && !password.isEmpty()) {
            replacementPassword = password;
        } else {
            List<Path> resources = hotReplacementContext.getResourcesDir();
            if (!resources.isEmpty()) {
                //TODO: fix this
                File appConfig = resources.get(0).resolve("application.properties").toFile();
                if (appConfig.isFile()) {
                    try (InputStream pw = new FileInputStream(appConfig)) {
                        Properties p = new Properties();
                        p.load(pw);
                        replacementPassword = p.getProperty(HotReplacementWebsocketEndpoint.QUARKUS_LIVE_RELOAD_PASSWORD);
                    } catch (IOException e) {
                        logger.error("Failed to read application.properties", e);
                    }
                }
            }
        }
        if (replacementPassword != null) {
            logger.info("Using websocket based hot deployment");
        } else {
            return;
        }
        try {
            hotReplacementContext.addPreScanStep(new Runnable() {
                @Override
                public void run() {
                    HotReplacementWebsocketEndpoint.checkForChanges(hotReplacementContext);
                }
            });
            //we need a special websocket setup
            //this will likely change
            //but we create a servlet deployment that lasts for the life of the server
            WebSocketDeploymentInfo info = new WebSocketDeploymentInfo();
            info.addEndpoint(HotReplacementWebsocketEndpoint.class);

            DeploymentInfo d = new DeploymentInfo();
            d.setDeploymentName("hot-replacement-websockets");
            d.setContextPath("/");
            d.setClassLoader(getClass().getClassLoader());
            d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info);
            ServletContainer servletContainer = Servlets.defaultContainer();
            DeploymentManager manager = servletContainer.addDeployment(d);
            manager.deploy();
            HttpHandler ws = manager.start();
            UndertowDeploymentRecorder.addHotDeploymentWrapper(new HandlerWrapper() {
                @Override
                public HttpHandler wrap(HttpHandler handler) {
                    return Handlers.predicate(Predicates.path(HotReplacementWebsocketEndpoint.QUARKUS_HOT_RELOAD), ws, handler);
                }
            });

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

@@ -45,16 +45,47 @@
 yment;%0A%0A
+import java.io.BufferedReader;%0A
 import j
@@ -177,32 +177,108 @@
 io.InputStream;%0A
+import java.io.InputStreamReader;%0Aimport java.nio.charset.StandardCharsets;%0A
 import java.nio.
@@ -2089,18 +2089,18 @@
 tStream 
-pw
+is
  = new F
@@ -2124,24 +2124,218 @@
 pConfig)) %7B%0A
+                        try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) %7B%0A                            try (BufferedReader br = new BufferedReader(isr)) %7B%0A        
             
@@ -2407,20 +2407,36 @@
     
+        
 p.load(
-pw
+br
 );%0A
+        
     
@@ -2478,16 +2478,57 @@
 word = p
+%0A                                        
 .getProp
@@ -2587,32 +2587,88 @@
 LOAD_PASSWORD);%0A
+                            %7D%0A                        %7D%0A
                 

Make sure we read properties with UTF8 encoding during live-reload