package org.wanna.jabbot.binding.matrix;

import com.sipstacks.xhml.Emojiify;
import com.sipstacks.xhml.XHTMLObject;
import com.sipstacks.xhml.XHtmlConvertException;
import de.jojii.matrixclientserver.Bot.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

class HtmlReformat {
    private String formattedMessage;
    private Client client;

    private final Logger logger = LoggerFactory.getLogger(HtmlReformat.class);

    public HtmlReformat(Client client, String formattedMessage) {
        this.client = client;
        this.formattedMessage = formattedMessage;
    }

    private void updateImages(NodeList nodeList) throws IOException {
        for(int i = 0; i < nodeList.getLength(); i++ ) {
            Node item = nodeList.item(i);
            if(item.getNodeType() != Node.TEXT_NODE) {
                if(item.getNodeName().equalsIgnoreCase("img")){
                    Node url = item.getAttributes().getNamedItem("src");
                    if (url != null) {
                        URL obj = new URL(url.getTextContent());
                        URLConnection con = obj.openConnection();
                        HttpURLConnection http = (HttpURLConnection) con;
                        http.setRequestMethod("GET");
                        http.connect();
                        http.getInputStream();

                        String newUrl;
                        synchronized (client) {
                            client.sendFile(http.getContentType(),http.getContentLength(),http.getInputStream(), result -> {
                                String s = result.toString();
                                if(s.startsWith("mxc")) {
                                    url.setTextContent(s);
                                }
                                client.notify();
                            });
                            try {
                                client.wait();
                            } catch (InterruptedException e) {
                                logger.error("Interruped on updating url", e);
                            }

                        }
                    }
                }
                NodeList childNodes = item.getChildNodes();
                if(childNodes != null) updateImages(childNodes);
            }
        }

    }

    public String invoke() {
        XHTMLObject obj = new XHTMLObject();
        try {
            obj.parse(formattedMessage);
            updateImages(obj.objects);
            Emojiify.convert(obj);
            formattedMessage = obj.getString();

        } catch (IOException | XHtmlConvertException | TransformerException e) {
            logger.error("unable to parse xhtml", e);
        }
        return formattedMessage;
    }
}

@@ -1532,24 +1532,25 @@
 .connect();%0A
+%0A
             
@@ -1565,32 +1565,108 @@
     
-http.getInputStream(
+synchronized (client) %7B%0A                            logger.info(%22mapping %22 + url.getTextContent()
 );%0A
-%0A
     
@@ -1689,70 +1689,154 @@
     
-String newUrl;%0A                        synchronized (client) %7B
+    logger.info(%22content-type: %22 +  http.getContentType());%0A                            logger.info(%22content-length: %22 + http.getContentLength());
 %0A   
@@ -1957,16 +1957,58 @@
 lt -%3E %7B%0A
+                                try %7B%0A    
         
@@ -2093,18 +2093,98 @@
         
+  
-if
+  logger.info(%22Result of upload: %22 + s);%0A                                    if 
 (s.start
@@ -2235,16 +2235,20 @@
         
+    
 url.setT
@@ -2258,24 +2258,206 @@
 Content(s);%0A
+                                    %7D%0A                                %7D catch(Exception e) %7B%0A                                    logger.error(%22Got an exception on image upload%22, e);%0A
             

add more logging