package org.kobjects.nativehtml.io;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import org.kobjects.nativehtml.dom.Platform;

public class DefaultRequestHandler implements RequestHandler {

  private final Platform platform;
  private TreeMap<String,String> internalLinkPrefixMap = new TreeMap<>();
  private InternalLinkHandler internalLinkHandler;
  
  public DefaultRequestHandler(Platform platform) {
    this.platform = platform;
  }
  
  public void setInternalLinkHandler(InternalLinkHandler internalLinkHandler) {
    this.internalLinkHandler = internalLinkHandler;
  }
  
  @Override
  public void openLink(URI url) {
    if (internalLinkHandler != null) {
      String s = url.toString();
      // TODO: Take advantage of order and start scan just before s.
      for (Map.Entry<String,String> entry : internalLinkPrefixMap.entrySet()) {
        if (s.startsWith(entry.getKey())) {
          openInternalLink(URI.create(entry.getValue() + s.substring(entry.getKey().length())));
          return;
        }
      }
    }
    platform.openInBrowser(url);
  }

  public void openInternalLink(URI url) {
    // TODO: Async
    try {
      internalLinkHandler.loadHtml(new InputStreamReader(url.toURL().openStream(), "utf-8"), url);
    } catch(IOException e) {
      throw new RuntimeException(e);
    }
  }

  public void addInternalLinkPrefix(String prefix) {
    internalLinkPrefixMap.put(prefix, prefix);
  }

  public void addInternalLinkPrefix(String prefix, String replacement) {
    internalLinkPrefixMap.put(prefix, replacement);
  }

}

@@ -117,56 +117,8 @@
 RI;%0A
-import java.util.Map;%0Aimport java.util.TreeMap;%0A
 impo
@@ -303,19 +303,12 @@
 Tree
-Map%3CString,
+Set%3C
 Stri
@@ -329,19 +329,19 @@
 nkPrefix
-Map
+Set
  = new T
@@ -343,19 +343,19 @@
 new Tree
-Map
+Set
 %3C%3E();%0A  
@@ -836,38 +836,21 @@
 or (
-Map.Entry%3CString,String%3E entry
+String prefix
  : i
@@ -870,22 +870,11 @@
 efix
-Map.entry
 Set
-()
 ) %7B%0A
@@ -898,30 +898,22 @@
 rtsWith(
-entry.getKey()
+prefix
 )) %7B%0A   
@@ -940,75 +940,11 @@
 ink(
-URI.create(entry.getValue() + s.substring(entry.getKey().length()))
+url
 );%0A 
@@ -1312,22 +1312,17 @@
 (String 
-prefix
+s
 ) %7B%0A    
@@ -1343,166 +1343,23 @@
 efix
-Map.put(prefix, prefix);%0A  %7D%0A%0A  public void addInternalLinkPrefix(String prefix, String replacement) %7B%0A    internalLinkPrefixMap.put(prefix, replacement
+Set.add(s
 );%0A  %7D%0A%0A
 %7D%0A
@@ -1356,10 +1356,11 @@
 );%0A  %7D%0A%0A
+%0A
 %7D%0A

revert prefix map support