package com.algobase.share.activity;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;

import android.graphics.Bitmap;
import android.graphics.Color;

import android.os.Bundle;
import android.os.Build;

import android.text.Spanned;

import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.HttpAuthHandler;

import android.net.Uri;
import android.net.http.SslError;

import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Toast;

import android.widget.FrameLayout.LayoutParams;

import com.algobase.share.system.*;
import com.algobase.share.dialog.*;
import com.algobase.share.compat.*;


public class WebViewActivity extends Activity
{

   static int full_screen = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

    String home_url = "http://www.google.de";
    //int scale = 100;
    int scale = 200;
    
    WebView web_view;
    MyProgressDialog progress_dialog;

    Display display;

    void show_toast(final String toast) {
      final Context ctxt = this;
      runOnUiThread( new Runnable() {
         public void run() {
           Toast.makeText(ctxt, toast, Toast.LENGTH_SHORT).show();
         }
      });
    }

    void load_url(String url)
    { web_view.setInitialScale(100);
      web_view.loadUrl(url);
      show_toast(url);
     }

  void progress_start(final String txt) 
  { 
    if (progress_dialog != null) return;

    progress_dialog = new MyProgressDialog(this);

    runOnUiThread(new Runnable() {
         public void run() { 
           Spanned msg = HtmlCompat.fromHtml("<big>" + txt + "</big>");
           progress_dialog.setMessage(msg);
           progress_dialog.setProgressStyle(MyProgressDialog.PROGRESS_STYLE_SPINNER);
           progress_dialog.show();
        }
    });
  }

  void progress_finish() 
  { if (progress_dialog == null) return;
    runOnUiThread(new Runnable() {
         public void run() { 
           if (progress_dialog.isShowing()) progress_dialog.dismiss(); 
           progress_dialog = null;
         }
    });
  }


	
    @Override
    public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     web_view = new WebView(this);

     setContentView(web_view);

     if (Build.VERSION.SDK_INT >= 35)
     { Resources res = getResources();

       int id = res.getIdentifier("status_bar_height","dimen","android");
       int margin_top = res.getDimensionPixelSize(id);

       id = res.getIdentifier("navigation_bar_height","dimen","android");
       int margin_bot = res.getDimensionPixelSize(id);

       ((LayoutParams)web_view.getLayoutParams()).topMargin = margin_top;
       ((LayoutParams)web_view.getLayoutParams()).bottomMargin = margin_bot;
    }


     WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
     display = wm.getDefaultDisplay(); 

        
     Intent intent = getIntent();

     home_url = intent.getStringExtra("url");
     scale = intent.getIntExtra("scale",100);

     web_view.setWebViewClient(new MyWebViewClient(this));
     web_view.setWebChromeClient(new MyWebChromeClient(this));
     web_view.getSettings().setJavaScriptEnabled(true);
/*
     web_view.getSettings().setLoadWithOverviewMode(true);
     web_view.getSettings().setUseWideViewPort(true);
*/
 
     web_view.getSettings().setBuiltInZoomControls(true);

     //web_view.getSettings().setDisplayZoomControls(true);
     web_view.getSettings().setDisplayZoomControls(false);
   
    web_view.setVerticalScrollBarEnabled(false);
    web_view.setHorizontalScrollBarEnabled(false);

    web_view.setInitialScale(scale);

    web_view.setDownloadListener(new DownloadListener() {
          public void onDownloadStart(String url, String userAgent,
                            String contentDisposition, String mimetype,
                            long contentLength) {
           Intent i = new Intent(Intent.ACTION_VIEW);
           i.setData(Uri.parse(url));
           startActivity(i);
          }
    });
          

    web_view.loadUrl(home_url);

  }

  @Override
  public void onResume() { 
     super.onResume();
  }

  @Override
  public void onBackPressed() { 
    if (web_view.canGoBack())
      web_view.goBack();
    else
      super.onBackPressed();
    //finish();
   }

    
    private class MyWebViewClient extends WebViewClient {
    	WebViewActivity activity;
        int load_count = 0;
    	
    	MyWebViewClient(WebViewActivity act) { activity = act; }

    	@Override
    	public void onReceivedHttpAuthRequest(WebView view, 
                                              HttpAuthHandler handler,
                                              String host,
                                              String realm)
       {
          //show_toast("onReceivedHttpAuthRequest: " + host.toString());
          handler.proceed("root","casamaria");
        }
 

/*
    	@Override
        public void onReceivedSslError(WebView view, 
                                       final SslErrorHandler handler, 
                                       SslError error) 
        {
           show_toast("onReceivedSslError: " + error.toString());
           handler.cancel();
         }
*/


/*
    	@Override
        public void onReceivedSslError(WebView view, 
                                       final SslErrorHandler handler, 
                                       SslError error) 
        {
           AlertDialog.Builder builder = 
                          new AlertDialog.Builder(WebViewActivity.this);

           String message = "SSL Certificate error.";
               switch (error.getPrimaryError()) {
                   case SslError.SSL_UNTRUSTED:
                       message = "The certificate authority is not trusted.";
                       break;
                   case SslError.SSL_EXPIRED:
                       message = "The certificate has expired.";
                       break;
                   case SslError.SSL_IDMISMATCH:
                       message = "The certificate Hostname mismatch.";
                       break;
                   case SslError.SSL_NOTYETVALID:
                       message = "The certificate is not yet valid.";
                       break;
               }

            builder.setTitle("SSL Certificate Error");
            builder.setMessage(message);

             builder.setPositiveButton("continue", 
                  new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         handler.proceed();
                     }
              });

             builder.setNegativeButton("cancel", 
                  new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         handler.cancel();
                     }
             });

            AlertDialog dialog = builder.create();
            dialog.show();
        }
*/
   	
    	
    	@Override
    	public void onPageStarted(WebView view, String url, Bitmap bmp) {
            //show_toast("onPageStarted: " + url);
            //progress_start(url);
    	}
    	
    	@Override
    	public void onPageFinished(WebView view, String url) {
            //show_toast("onPageFinished: " + url);
            new MyThread() {
               public void run() { 
                   runOnUiThread( new Runnable() {
                          public void run() { 
                          }
                   });
/*
                  sleep(1000);
                  progress_finish();
*/
               }
            }.start();
    	}
    	
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //show_toast("shouldOverrideUrlLoading");
            //show_toast(url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, 
                                    String description, String failingUrl) 
        {
            show_toast("Error: " + description);
          }
    }
    

    private class MyWebChromeClient extends WebChromeClient {
    	WebViewActivity activity;
    	
    	MyWebChromeClient(WebViewActivity act) { activity = act; }
         
        @Override
        public void onProgressChanged(WebView view, int progress) {
             //activity.setProgress(progress*100 );
         }    
    }

}
