package com.sabirjan.android;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Stack;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;


import com.sabirjan.android.R;
import com.sabirjan.liulanqi.Dialog.CustomizeDialog;
import com.sabirjan.liulanqi.Dialog.Dialog_InputURL;
import com.sabirjan.liulanqi.Dialog.InfoDialog;
import com.sabirjan.liulanqi.Dialog.MyListener;
import com.sabirjan.liulanqi.Mytest.ConvertUL;
import com.sabirjan.liulanqi.Wangluo.HtmlChuli;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class TSNews_Activity extends Activity {
    /** Called when the activity is first created. */
	
private RadioGroup mainRadio;
	
	
	WebView web;
	RadioButton r0,r1,r2,r3,r4,r5;
	Animation animation;  
	ProgressBar pb; 
	boolean isConn=true;
	private static final int ABOUT = 1;  
    private static final int EXIT = 2;  
    HtmlChuli clsHTML;
    ConvertUL cls=new ConvertUL();
    Stack shtml=new Stack();
      // String urlBase="http://www.uqur.cn";
	String oldHtml="http://bbs.misranim.com/simple/";
	String strHtml="";
	String Strurl="http://bbs.misranim.com/simple/";
	public static boolean isNew=false;
	  Handler handler;
	  MyHandler my;
	  HandlerThread myHandlerThread;
	  String []strFiletype={".jpg",".gif",".png",".bmp"};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //
		this.setContentView(R.layout.main_tabs);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);//
		
	//	requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //
	//	getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);//
	//    inputUrl=(AutoCompleteTextView)findViewById(R.id.txt_url);
		SetFont();
		copyFile(this, "UKIJTuT.ttf");
		DisplayMetrics dm=new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			int width=dm.widthPixels;
			int height=dm.heightPixels;
		
			System.out.println("W="+width+"H="+height);
			
			mainRadio=(RadioGroup)this.findViewById(R.id.main_radio);
			mainRadio.setOnCheckedChangeListener(new OnCheckedChangeListener(){
		
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch(checkedId)
				{
		//		case R.id.button_0:ShowDialog();break;
				case R.id.button_1:ShuaXin();break;
				case R.id.button_2:
				if(shtml.size()>0)
				{
					GoBack();
				}
				else
				{
					 CustomizeDialog clsDialog=new CustomizeDialog(TSNews_Activity.this);
			      	 clsDialog.show();
				}
				
				break;
				case R.id.button_3:break;
				case R.id.button_4:TingZhi();break;
			//	case R.id.button_5:SheZhi();break;
				}
				
			}
			
			
		});//End setOnCheckedChangeListener
		
		/////////////////////
		
		clsHTML=new HtmlChuli();
		pb=(ProgressBar)this.findViewById(R.id.pb_1);
		pb.setMax(100);
		pb.setVisibility(View.VISIBLE);
		pb.setProgress(10);
	 	web=(WebView)findViewById(R.id.web_1);
	    web.getSettings().setJavaScriptEnabled(true);
	    web.getSettings().setLoadsImagesAutomatically(true);
	    web.getSettings().setSupportZoom(true);
	    web.getSettings().setBuiltInZoomControls(true);
	//    
	   
	    web.getSettings().setPluginsEnabled(true);
	    web.getSettings().setBlockNetworkImage(false);
	    web.getSettings().setUserAgentString("Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10");
	    web.isClickable();
	    web.getSettings().setSupportMultipleWindows(false);//buzhichi  duo chuangkou  xianshi ,...
	    
	   // web.getSettings().setCacheMode(0x00000001);
	    myHandlerThread=new HandlerThread("MyThrad");
	    myHandlerThread.start();
	    my=new MyHandler(myHandlerThread.getLooper());
	    Message m=my.obtainMessage();
	    m.obj=oldHtml;
	    m.arg1=0;
	    isNew=false;
	    m.sendToTarget();
	    web.setInitialScale(85);   
	  //  handler.post(runable);
	    web.setWebViewClient(new MyWebClinet());
	    
	    web.setWebChromeClient(new MyWebChromeClient());
	    
    }
    class MyWebChromeClient extends WebChromeClient
    {
    	@Override
		public void onProgressChanged(WebView view,	int newProgress)
    	{
			if(newProgress<100)
			{
				if(pb.getVisibility()==View.INVISIBLE)
				pb.setVisibility(View.VISIBLE);
				pb.setProgress(newProgress);
			}
			else
			{
				 isConn=false;
				pb.setVisibility(View.INVISIBLE);
			}
			super.onProgressChanged(view, newProgress);
		}
    	
    	
    	
    	
    	
    }
    
    
    class MyWebClinet extends WebViewClient
    {
    	  	@Override
			public void onPageFinished(WebView view, String url) 
    	  	{
    	  		 isConn=false;
    	  		super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url,
					Bitmap favicon) {
				
				super.onPageStarted(view, url, favicon);
			}

			public boolean shouldOverrideUrlLoading(WebView view, String url) 
			{ 
				
				
				
				for(String str:strFiletype)
				{
					if(url.toLowerCase().trim().endsWith(str))
					{
						SheZhi(" ﺭﻩﺳﯩﻢ ﻛﯚﺭﯗﺵ ﺋﯩﻘﺘﯩﺪﺍﺭﻯ ﻗﻮﺷﯘﻟﻤﯩﺪﻯ");
						return true;
					}
				}
				System.out.println(url);
				if(url==oldHtml)
				{
					System.out.println("AAAAAAA"+url);
						return true;
				}
				if(isConn==false)
				{
				
					shtml.push(strHtml);
					isConn=true;
					System.out.println("is Stoped");
			  	    isNew=true;
			  	 	web.stopLoading();
			  		System.out.println("is Stoped----------------");
			  		pb.setVisibility(View.VISIBLE);
			  		pb.setProgress(10);
			    	Message m=my.obtainMessage();
			 	    m.obj=url;
			 	    m.arg1=1;
			 	    m.sendToTarget();
				}
				else
				{
					System.out.println("BBBBBBBB"+url);
				}
				return true; 
	    	}

			@Override
			public void onReceivedError(WebView view,int errorCode, String description,String failingUrl) 
			{
				 isConn=false;
				super.onReceivedError(view, errorCode, description, failingUrl);
			} 
			
    }//End WebViewClinet Class
    
    private void SheZhi()
    {
    	InfoDialog info=new InfoDialog(this);
    	info.show();
    }
    private void SheZhi(String strInfo)
    {
    	InfoDialog info=new InfoDialog(this,strInfo);
    	info.show();
    }
    private void ShuaXin()
    {
    	if(oldHtml.length()>0)
    	{
    		isNew=true;
    		web.stopLoading();
    		pb.setVisibility(View.VISIBLE);
	  		pb.setProgress(10);
	    	Message m=my.obtainMessage();
	 	    m.obj=oldHtml;
	 	    m.arg1=0;
	 	    isNew=false;
	 	    m.sendToTarget();
    	}
    	r3.setChecked(true);
    }
    
    private void TingZhi()
    {
    	if(isNew==false)
    	{
    	 	web.stopLoading();
    		pb.setVisibility(View.INVISIBLE);
    		isNew=true;
    		isConn=false;
    		r3.setChecked(true);
    	}
    }
    public  void ShowDialog()
	  {
    	

    	/*
    	Dialog_InputURL dialg=new Dialog_InputURL(this,new MyListener()
    	{

			@Override
			public void refreshActivity(String url) {
				// TODO Auto-generated method stub
				if(url.length()>0)
				{
					if(strHtml.length()>0)
					{
				 	    shtml.push(strHtml);
					}
					System.out.println("is Stoped");
			  	    isNew=true;
			  		System.out.println("is Stoped----------------");
			  		pb.setVisibility(View.VISIBLE);
			  		pb.setProgress(10);
			    	Message m=my.obtainMessage();
			 	    m.obj=url;
			 	    m.arg1=0;
			 	    Strurl=url+"/";
			 	 	web.stopLoading();
			 	    m.sendToTarget();
				}
				r3.setChecked(true);
			}
    		
    		
    	});
    	dialg.show();
    	*/
    	
	  }
    
    private void SetFont()
	{
		
		r1=(RadioButton)this.findViewById(R.id.button_1);
		r2=(RadioButton)this.findViewById(R.id.button_2);
		r3=(RadioButton)this.findViewById(R.id.button_3);
		r4=(RadioButton)this.findViewById(R.id.button_4);
		TextView txt_title=(TextView)this.findViewById(R.id.txt_title);
		Typeface typeface=Typeface.createFromAsset(this.getAssets(),"fonts/UKIJTuT.ttf");
		r1.setTypeface(typeface);
		r2.setTypeface(typeface);
		r3.setTypeface(typeface);
		r4.setTypeface(typeface);
		
		txt_title.setText(" ﺗﯩﻴﺎﻧﺸﺎﻥ ﺗﻮﺭﻯ");
		txt_title.setTypeface(typeface);
		}
    //////////////////////////////////////////////
    
    
    class MyHandler extends Handler
    {
    	
    	  private Element SetElmentCSSURL(Element sourceEl)
			{
				String sourceTag=sourceEl.tagName();
				Attributes destAttrs=new Attributes();
				
				Element dest=new Element(Tag.valueOf(sourceTag),sourceEl.baseUri(),destAttrs);
				Attributes sourceAttrs=sourceEl.attributes();
				for(Attribute sourceAttr:sourceAttrs)
				{
					
					if(sourceAttr.getKey().contains("href"))
					{	
						if(!sourceAttr.getValue().contains("http://"))
						{
							sourceAttr.setValue(Strurl+sourceAttr.getValue());
						}
						
					}
					destAttrs.put(sourceAttr);
				}
				
				return dest;
				}
    	  private Element SetElmentIMGURL(Element sourceEl)
			{
				String sourceTag=sourceEl.tagName();
				Attributes destAttrs=new Attributes();
				
				Element dest=new Element(Tag.valueOf(sourceTag),sourceEl.baseUri(),destAttrs);
				Attributes sourceAttrs=sourceEl.attributes();
				for(Attribute sourceAttr:sourceAttrs)
				{
					
					if(sourceAttr.getKey().contains("src"))
					{	
						if(!sourceAttr.getValue().contains("http://"))
						{
							sourceAttr.setValue(Strurl+sourceAttr.getValue());
						}
						
					}
					destAttrs.put(sourceAttr);
				}
				
				return dest;
				}
  	
    	public MyHandler()
    	{
    		
    	}
    	public MyHandler(Looper looper)
    	{
    		super(looper);
    	}
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			String text="";
			System.out.println("MMMMMMMMMMMMM"+msg.arg1);
			
			
			
			
			  try {
		//	  pb.setVisibility(View.VISIBLE);
		//	   pb.setProgress(10);
				  String  baseUrl="";
				  if(msg.arg1==1)
					{
						if(!msg.obj.toString().contains("http://"))
						{
							baseUrl=Strurl+msg.obj.toString();
						}
						else
						{
							baseUrl=msg.obj.toString();
						}
					}
				  else
				  {
					  baseUrl=Strurl;
				  }
				  	if(isNew&oldHtml!=baseUrl)
					{
						isNew=false;
					}
					else if(isNew)
					{
						return;
					}
			   oldHtml=baseUrl;
			   System.out.println("aaaaaaaaaaaaaaaaaaaaaaaa"+(String)baseUrl);
			   strHtml=clsHTML.GetHtmlCode(baseUrl);
			   if(isNew)
				{
	        		 return;
	        	}
					strHtml=strHtml.toLowerCase();
					Document dirtyDocument = Jsoup.parse(strHtml);
			         ConvertUL cls=new ConvertUL();
			         strHtml="";
			     	pb.setProgress(20);
			         Elements links =dirtyDocument.getElementsByAttribute("body");
			        
			         String txt=cls.GetULUyghurWord(links.html());
			         System.out.println(txt);
			         links.html(txt);
			  
			         if(isNew)
						{
		        		 return;
		        	 }
			         strHtml=dirtyDocument.outerHtml();	    
			        

			} catch (Exception e) {
				// TODO Auto-generated catch block
				try {
					
				strHtml=clsHTML.getErrorPage(TSNews_Activity.this);
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		
			if(isNew)
			{
				strHtml="";
        		 return;
        	 }
			strHtml=strHtml.toLowerCase();
				
			Document dirtyDocument = Jsoup.parse(strHtml);
			
		       //  Elements links = doc.getAllElements();//select("body");
		         ConvertUL cls=new ConvertUL();
		         strHtml="";
		         Elements links =dirtyDocument.getAllElements();
		         for(int i=0;i<links.size();i++)
		         {
		        	 if(msg.arg1==-1)
		        	 {
		        		 return;
		        	 }
		        	 if(links.get(i).tagName()=="link")
		        	 {
		        		System.out.println("HHHH");
		        		Element el=SetElmentCSSURL(links.get(i));
		        		links.get(i).html(el.html());	
		        		 continue;
		        	 }
		        	 if(links.get(i).tagName()=="img")
		        	 {
		        		 
		        		 System.out.println("HHHH");
		        		 Element el=SetElmentIMGURL(links.get(i));
		        		 links.get(i).html(el.html());	
		        		 continue;
		        		 
		        	 }
		        	 if(links.get(i).children().size()==0)
		        	 {
		       // 		 System.out.println(links.get(i).tagName());
		        		 String txt=links.get(i).text();
		        		 txt=cls.GetULUyghurWord(txt);
		        		 links.get(i).text(txt);
		        	 }
		        	
		        	 else if(links.get(i).hasText()&links.get(i).tagName()=="div")
		        	 {
		        		 String txt=links.get(i).outerHtml();
		        		 txt=cls.GetULUyghurWord(txt);
		        		 links.get(i).html(txt);
		        		//SetElmenet(links.get(i).getAllElements());
		        		
		        	 }
		         }
		         strHtml=dirtyDocument.outerHtml();	
			}
			
				strHtml=clsHTML.getHtmlData(strHtml,TSNews_Activity.this);
 			  System.out.println("bbbbbbbbbbbbbbbbbbbbbbb");
 			 if(isNew)
 			{
 				strHtml="";
        		 return;
        	 }
 			 
 			 //about:blank
 			 web.loadDataWithBaseURL("about:blank",strHtml, "text/html", "utf-8",null);
 			// web.loadData(strHtml,  "text/html", "utf-8"); 
 			 isConn=false;
 			  System.out.println("cccccccccccccccccccccc");
			
		}
    	
    }
    
    
    ///////////
    
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // TODO Auto-generated method stub  
         // MenuInflater inflater = new MenuInflater(getApplicationContext());  
        // inflater.inflate(R.menu.options_menu, menu);  
        menu.add(0, ABOUT, 1, "关于");  
        menu.add(0, EXIT, 2, "退出");  
     
        return true;  

        
    }  

  @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        // TODO Auto-generated method stub  
        int id = item.getItemId();  
        switch (id) {  
        case ABOUT: //濡傛灉浣跨敤xml鏂瑰紡锛岃繖閲屽彲浠ヤ娇鐢≧.id.about 
        	  
              break;  
        case EXIT: //鍚屼笂  
      	  CustomizeDialog clsDialog=new CustomizeDialog(this);
      	  clsDialog.show();
        //    android.os.Process.killProcess(android.os.Process.myPid());  
      //	  System.exit(0);
        }  
        return super.onOptionsItemSelected(item);  
    }  
  private void GoBack()
  {
	  	isNew=true;
		String html=(String)shtml.pop();
	  	strHtml=html;
	  	isNew=false;
	  	web.stopLoading();
	  	web.loadDataWithBaseURL("about:blank",html, "text/html", "utf-8",null);
		r3.setChecked(true);
  }

  
  ////////////
  private boolean copyFile(Context context,String fileName) {
      boolean status = false;
      try { 
          FileOutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
          InputStream in = context.getAssets().open(fileName);
          
          // Transfer bytes from the input file to the output file
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
              out.write(buf, 0, len);
          }
          // Close the streams
          out.close();
          in.close();
          status = true;
      } catch (Exception e) {
          System.out.println("Exception in copyFile:: "+e.getMessage());
          status = false;
      }
      System.out.println("copyFile Status:: "+status);
      return status;
  }
  ////////////
  
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
  	// TODO Auto-generated method stub
  	if(KeyEvent.KEYCODE_BACK==keyCode&shtml.size()>0)
  	{
  		GoBack();
  		 return true;
  	}
  	else if(KeyEvent.KEYCODE_BACK==keyCode)
  	{
  		  CustomizeDialog clsDialog=new CustomizeDialog(this);
      	  clsDialog.show();
      	  return true;
  	}
  	else
  	{
  		return super.onKeyDown(keyCode, event);
  	}
  }

@Override
public void onConfigurationChanged(Configuration newConfig) {
	// TODO Auto-generated method stub
	super.onConfigurationChanged(newConfig);
}
    
}