package com.periplanisi.android.webwrapper.web;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.periplanisi.android.webwrapper.settings.SettingsHelper;

/**
 * Basic WebViewClient implementation
 * 
 * @author Ioannis Panagiotopoulos <ipanag+android@gmail.com>
 *
 */
public class WrapperWebViewClient extends WebViewClient {
	
	private static final String TAG = "WebClient";
	
	private final WeakReference<Activity> activityWeakRef;
	private String loadUrl;
	private SettingsHelper settingsHelper;
	private boolean loading = false;
	
	public WrapperWebViewClient(Activity activity, SettingsHelper settingsHelper) {
		this.activityWeakRef = new WeakReference<Activity>(activity);
		this.settingsHelper = settingsHelper;
	}
	
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    	Log.d(TAG, "shouldOverride: " + url);
    	
    	boolean openExternal = settingsHelper.isOpenOtherHostLinks();
    	boolean openSameHost = settingsHelper.isOpenSameHostLinks();
    	
    	if(!openExternal || !openSameHost) {
	    	try {
	    		final Activity activity = activityWeakRef.get();
	        	if (activity != null) {
	        		Uri uri = Uri.parse(url);
	            	Uri loadedUri = Uri.parse(loadUrl);
	            	
	            	String loadedUriHost = loadedUri.getHost();
	            	String currentUriHost = uri.getHost();
	            	
	            	Log.d(TAG, "loadedUriHost: " + loadedUriHost + " currentUriHost: " + currentUriHost);
	            	
	            	if (loadedUriHost.equals(currentUriHost)) {
		        		if(!openSameHost) {
		        			fireUriIntent(activity, uri);
		        			return true;
		        		}
	            	} else {
	            		if(!openExternal) {
		        			fireUriIntent(activity, uri);
		        			return true;
		        		}
	            	}
	        	}
	        	
	    	} catch(final NullPointerException e) {
		    	e.printStackTrace();
		    }
    	}
    	return false;
    }
    
	/**
	 * Open Uri in external application (ie browser)
	 * 
	 * @param activity
	 * @param uri
	 */
    private void fireUriIntent(Activity activity, Uri uri) {
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		activity.startActivity(intent);
    }
    
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
    	super.onPageStarted(view, url, favicon);
    	
    	Log.d(TAG, "onPageStarted: " + url);
    	
    	// update stored url, in case of redirection
    	loadUrl = url;
    	loading = true;
    	
    	final Activity activity = activityWeakRef.get();
    	if (activity != null && activity instanceof WebPageLoadListener) {
    		((WebPageLoadListener)activity).onPageStartLoading();
    	}
    }
    
    @Override
    public void onPageFinished(WebView view, String url) {
    	super.onPageFinished(view, url);
    	
    	Log.d(TAG, "onPageFinished: " + url);
    	
    	if(loading) {
	    	final Activity activity = activityWeakRef.get();
	    	if (activity != null && activity instanceof WebPageLoadListener) {
	    		((WebPageLoadListener)activity).onPageLoadedSuccessfully();
	    	}
    	}
    	
    	loading = false;
    }
    
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    	super.onReceivedError(view, errorCode, description, failingUrl);
    	
    	Log.w(TAG, "onReceivedError: " + failingUrl);
    	
    	loading = false;
    	
    	final Activity activity = activityWeakRef.get();
    	if (activity != null && activity instanceof WebPageLoadListener) {
    		((WebPageLoadListener)activity).onPageLoadedFailure(errorCode, description, failingUrl);
    	}
    }
    
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
    	if(settingsHelper.isIgnoreSslError()) {
    		handler.proceed();
    	} else {
    		handler.cancel();
    	}
    }
    
}

@@ -254,16 +254,55 @@
 il.Log;%0A
+import android.webkit.HttpAuthHandler;%0A
 import a
@@ -324,32 +324,32 @@
 slErrorHandler;%0A
-
 import android.w
@@ -849,16 +849,52 @@
  false;%0A
+%09private String username, password;%0A
 %09%0A%09publi
@@ -2663,60 +2663,8 @@
 ) %7B%0A
-    %09super.onPageStarted(view, url, favicon);%0A    %09%0A
     
@@ -3085,52 +3085,8 @@
 ) %7B%0A
-    %09super.onPageFinished(view, url);%0A    %09%0A
     
@@ -3518,84 +3518,8 @@
 ) %7B%0A
-    %09super.onReceivedError(view, errorCode, description, failingUrl);%0A    %09%0A
     
@@ -4065,15 +4065,497 @@
 %7D%0A    %7D%0A
-
     %0A
+    @Override%0A    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) %7B%0A    %09Log.w(TAG, %22onReceivedHttpAuthRequest: %22 + realm);%0A    %09%0A    %09if(username != null && password != null) %7B%0A    %09    handler.proceed(username, password);%0A    %09%7D else %7B%0A    %09    handler.cancel();%0A    %09%7D%0A    %7D%0A%0A    public void setUsernamePassword(String username, String password) %7B%0A        this.username = username;%0A        this.password = password;%0A    %7D%0A%0A
 %7D%0A

Add support for webViewClient handling http auth request