package com.kickstarter.services;

import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.kickstarter.libs.Build;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class KickstarterWebViewClient extends WebViewClient {
  private final Build build;

  public KickstarterWebViewClient(final Build build) {
    this.build = build;
  }

  @Override
  public WebResourceResponse shouldInterceptRequest(final WebView view, final WebResourceRequest request) {
    if (!isInterceptable(request)) {
      return null;
    }

    final HttpGet httpGet = new HttpGet(request.getUrl().toString());
    httpGet.setHeader("Kickstarter-Android-App", build.versionCode().toString());
    try {
      final HttpResponse response = new DefaultHttpClient().execute(httpGet);
      final MimeHeaders mimeHeaders = new MimeHeaders(response.getEntity().getContentType());

      return new WebResourceResponse(mimeHeaders.type,
        mimeHeaders.encoding,
        response.getStatusLine().getStatusCode(),
        response.getStatusLine().getReasonPhrase(),
        headers(response),
        response.getEntity().getContent());
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  @Override
  public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
    return false;
  }

  protected boolean isInterceptable(final WebResourceRequest request) {
    // TODO: Check injected host rather than 'www.kickstarter.com' - e.g. if we change endpoints
    // TODO: Fix up support for lower API versions
    if (!request.getUrl().getHost().equals("www.kickstarter.com")) {
      return false;
    }

    // TODO: Add more endpoints, make pattern matching more robust
    return Pattern.compile("/pledge/new").matcher(request.getUrl().toString()).find();
  }

  protected Map<String,String> headers(final HttpResponse response) {
    final Map<String,String> headers = new HashMap<String,String>();
    final HeaderIterator iterator = response.headerIterator();
    while(iterator.hasNext()) {
      Header header = iterator.nextHeader();
      headers.put(header.getName(), header.getValue());
    }
    return headers;
  }


  public class MimeHeaders {
    public String type = null;
    public String encoding = null;

    public MimeHeaders(final Header header) {
      if (header == null) {
        return;
      }

      // Extract mime and encoding from string, e.g. "text/html; charset=utf-8"
      final Matcher matcher = Pattern.compile("([\\w\\/]+); charset=([\\w/-]+)")
        .matcher(header.getValue());
      if (matcher.matches()) {
        type = matcher.group(1);
        encoding = matcher.group(2).toUpperCase();
      }
    }
  }
}

@@ -28,16 +28,40 @@
 vices;%0A%0A
+import android.net.Uri;%0A
 import a
@@ -862,34 +862,18 @@
 nal 
-WebResourceRequest request
+String url
 ) %7B%0A
@@ -897,23 +897,19 @@
 eptable(
-request
+url
 )) %7B%0A   
@@ -975,35 +975,11 @@
 Get(
-request.getUrl().toString()
+url
 );%0A 
@@ -1296,24 +1296,16 @@
 rs.type,
-%0A       
  mimeHea
@@ -1322,145 +1322,8 @@
 ing,
-%0A        response.getStatusLine().getStatusCode(),%0A        response.getStatusLine().getReasonPhrase(),%0A        headers(response),%0A       
  res
@@ -1446,125 +1446,8 @@
  %7D%0A%0A
-  @Override%0A  public boolean shouldOverrideUrlLoading(final WebView view, final String url) %7B%0A    return false;%0A  %7D%0A%0A
   pr
@@ -1488,34 +1488,18 @@
 nal 
-WebResourceRequest request
+String url
 ) %7B%0A
@@ -1567,19 +1567,19 @@
 .com' - 
-e.g
+i.e
 . if we 
@@ -1603,80 +1603,52 @@
     
-// TODO: Fix up support for lower API versions%0A    if (!request.getUrl()
+final Uri uri = Uri.parse(url);%0A    if (!uri
 .get
@@ -1722,162 +1722,329 @@
     
-// TODO: Add more endpoints, make pattern matching more robust%0A    return Pattern.compile(%22
+return isProjectNewPledgeUrl(uri);%0A  %7D%0A%0A  protected boolean isProjectNewPledgeUrl(final Uri uri) %7B%0A    return Pattern.compile(%22%5C%5CA%5C%5C/projects/%5Ba-zA-Z0-9_-%5D+%5C%5C/%5Ba-zA-Z0-9_-%5D+%5C%5C
 /pledge
+%5C%5C
 /new
-%22).matcher(request.getUrl().toString()).find();%0A  %7D%0A
+%5C%5Cz%22)%0A      .matcher(uri.getPath()).matches();%0A  %7D%0A%0A  // Unused, useful if we use new WebResourceResponse constructor added in API 21
 %0A  p
@@ -2730,16 +2730,19 @@
 mpile(%22(
+%5C%5CA
 %5B%5C%5Cw%5C%5C/%5D
@@ -2763,16 +2763,19 @@
 %5C%5Cw/-%5D+)
+%5C%5Cz
 %22)%0A     

Fix up API compatibility, improve regexps