package fsenablers.android.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import fsenablers.android.BuildConfig;
import fsenablers.android.R;

import fsenablers.android.http.HttpDownloadTask;
import fsenablers.android.http.IHttpResponseListener;

public class MyWebViewClient extends WebViewClient implements IHttpResponseListener {
	
	public static final String TAG = "MyWebViewClient";
	
	private WebAppActivity activity;
	private String mHost;
	private List<String> whiteList;
	private List<String> docRootList;
	
	public MyWebViewClient( WebAppActivity activity ) {
		super();
		this.activity = activity;
		
		whiteList = new ArrayList<String>();
		docRootList = new ArrayList<String>();
		
		HttpDownloadTask downloadWhiteList = new HttpDownloadTask();
		downloadWhiteList.setListener( this );
		
		
		// downloadWhiteList.execute( "http://preview.fsenablers.com/mobile/urloptions.json" );
		// for production downloadWhiteList.execute( "http://www.appslibrary.com/mobileapps/crm/urloptions.json" );

		downloadWhiteList.execute( "https://www.appslibrary.com/mobileapps/crm/whitelist.json" );

	}
	
	public void onReceivedError( WebView wv, int errorCode, String description, String failingUrl ) {
		if( BuildConfig.DEBUG ) { Log.d( TAG, "onReceivedError( " + errorCode + ": " + description + ": " + failingUrl );}
	}
	
	public WebResourceResponse shouldInterceptRequest( WebView view, String url ) {
		if( BuildConfig.DEBUG ) { Log.d(TAG, "shouldInterceptRequest " + url );}
		return null;
	}
	
	public List<String> getWhiteList() {
		return Collections.unmodifiableList( whiteList );
	}
	
	public List<String> getDocRootList() {
		return Collections.unmodifiableList( docRootList );
	}
	
	public boolean isPartOfWebApp(String url ) {
		
		boolean bPartOfWebApp = false;
		
		Uri uriToLoad = Uri.parse( url );
		
		// some urls (tel: and mailto:) do not have a "host" - i.e. tel: mailto:
		if( uriToLoad.getHost() != null ) {
			if( uriToLoad.getHost().equalsIgnoreCase( activity.getHost() )) {
				bPartOfWebApp = true;
			} else {
				// check the actual white list
				Iterator<String> i = whiteList.iterator();
				while( !bPartOfWebApp && i.hasNext() ) {
					String whiteListURL = i.next();
					bPartOfWebApp = whiteListURL.equalsIgnoreCase( url );
				}
			}
		}
		
		return bPartOfWebApp;
		
	}
	
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		
		boolean bPartOfWebApp = isPartOfWebApp( url );
		
		if( BuildConfig.DEBUG ) { Log.d( TAG, "shouldOverrideUrlLoading " + url );}
		
		boolean shouldOverrideUrlLoading = false;
		if( bPartOfWebApp ) {
			shouldOverrideUrlLoading = false;
		} else {
			shouldOverrideUrlLoading = true;
			
			Uri uriToLoad = Uri.parse( url );
			
			if( BuildConfig.DEBUG ) { 
			Log.d( TAG, "host = " + uriToLoad.getHost());
			Log.d( TAG, "port = " + uriToLoad.getPort() );
			Log.d( TAG, "path = " + uriToLoad.getPath() );
			Log.d( TAG, "query = " + uriToLoad.getQuery( ));
			}
			
			Intent intent = new Intent(Intent.ACTION_VIEW, uriToLoad );
			activity.startActivity(intent);
			
		}
		
		if( BuildConfig.DEBUG ) { Log.d( TAG, "shouldOverrideUrlLoading = " + shouldOverrideUrlLoading );}
		return shouldOverrideUrlLoading;
		
	}
	
	public void onLoadResource( WebView view, String url ) {
		if( BuildConfig.DEBUG ) { Log.d( TAG, "onLoadResource( " + url + " )");}
	}
	
	public void onPageStarted( WebView view, String url, Bitmap favicon ) {
		if( BuildConfig.DEBUG ) { Log.d(TAG,  "onPageStarted( " + url + " )");}
	}
	
	public void onPageFinished( WebView view, String url ) {
		if( BuildConfig.DEBUG ) { Log.d(TAG, "onPageFinished( " + url + " )" );}
	}
	
	
	public void onHttpResponse( String responseText ) {
		
		try {
			
			JSONObject jsonObject = new JSONObject( responseText );
			JSONObject jsonWhiteList = jsonObject.getJSONObject( "whitelist" );
			JSONArray jsonHostNames = jsonWhiteList.getJSONArray( "hostnames" );
			
			for( int x = 0; x < jsonHostNames.length(); x++ ) {
				String url = jsonHostNames.getString( x );
				whiteList.add( url );
				if( BuildConfig.DEBUG ) { Log.d( "whitelist entry", url.toString() );}
				
				Uri uri = Uri.parse( url );
				if( uri.getQueryParameter( "native" ) != null ) {
					docRootList.add( url );
				}
			}
			
			Iterator<String> i = docRootList.iterator();
			
			if( BuildConfig.DEBUG ) { 
				while( i.hasNext() ) {
					Log.d( "DocRootURL", i.next().toUpperCase() );
				}
			}

		} catch( JSONException jx ) {
			Log.e( TAG, "JSON Error parsing whitelist: " + jx.getMessage() );
		}

	}
	
	
}
