package mh.adib.shiveh;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;

import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;


public class Show extends Activity {
	
	List<Ketab> ketab=new ArrayList<Ketab>();
	
	private DrawerLayout drawerLayout;
	private View drawerView;
	private SharedPreferences prefs;
	String str = null;
	Boolean exist_comment=false;
	ImageView fav;
	
	public List<Ketab> getketab()
	{
		return ketab;
	}
	Ketab ketab_obj;
	String parent;
	String child;
	String text;
	String id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.show);
		parent=String.valueOf(Integer.parseInt(getIntent().getExtras().get("parent").toString())+1);
		child=String.valueOf(Integer.parseInt(getIntent().getExtras().get("child").toString())+1);
		prefs = getPreferences(MODE_PRIVATE);
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawerView = (View) findViewById(R.id.drawer);
		
		InputStream is;
		try {
			is = getAssets().open(parent+"_"+child+".html");
			int size = is.available();

			byte[] buffer = new byte[size];
			is.read(buffer);
			is.close();

			str = new String(buffer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ImageView search=(ImageView)findViewById(R.id.search);
		search.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final Dialog dialog=new Dialog(Show.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
				dialog.setContentView(R.layout.custom_search);
		
				ImageView searchbtn=(ImageView)dialog.findViewById(R.id.custom_search_btn);
				searchbtn.setOnClickListener(new OnClickListener() {
					
					@SuppressLint("NewApi")
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						
						WebView mWebView = (WebView) findViewById(R.id.webView1);
						EditText et=(EditText)dialog.findViewById(R.id.custom_search_edit);
						mWebView.findAllAsync(et.getText().toString());
						
						dialog.dismiss();
						
						drawerLayout.closeDrawers();
					}
				});
			
				dialog.show();
			}
		});
		
		
		
		fav=(ImageView)findViewById(R.id.fav);
		int aa=ShowFav();
		if(aa==0)
			fav.setImageResource(R.drawable.fav1);
		else
			fav.setImageResource(R.drawable.fav);
		fav.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SQLiteDatabase mydb = openOrCreateDatabase("shiveh.db", Context.MODE_PRIVATE,null);
				try
	               {
						Cursor allrows  = mydb.rawQuery("SELECT * FROM shiveh WHERE ID='"+parent+"_"+child+"'", null);
						if(allrows.moveToFirst()){
		   	    	        do{
		   	    	        	if(Integer.parseInt(allrows.getString(2))==0)
		   	    	        	{
		   	    	        		mydb.execSQL("UPDATE shiveh SET fav=1  WHERE ID='"+parent+"_"+child+"'");
		   	    	        		fav.setImageResource(R.drawable.fav);
		   	    	        	}
		   	    	        	else
		   	    	        	{
		   	    	        		mydb.execSQL("UPDATE shiveh SET fav=0  WHERE ID='"+parent+"_"+child+"'");
		   	    	        		fav.setImageResource(R.drawable.fav1);
		   	    	        	}
		   	    	        }
		   	    	        while(allrows.moveToNext());
						}
						else
						{
							mydb.execSQL("INSERT INTO shiveh (ID,comment,Fav) VALUES ('"+parent+"_"+child+"',''"+",1)");
							fav.setImageResource(R.drawable.fav);
						}
	               }
	               catch (Exception e) {
					// TODO: handle exception
				}
				mydb.close();
				drawerLayout.closeDrawers();
				Toast.makeText(Show.this, "لیست علاقه‌مندی‌ها بروزرسانی شد.", Toast.LENGTH_LONG).show();
				//ShowFav();
			}
		});
		

		ImageView note=(ImageView)findViewById(R.id.note);
		note.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final Dialog dialog = new Dialog(Show.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
				dialog.setContentView(R.layout.custom_comment);
			
				//dialog.setTitle("یاد داشت برداری");

				// set the custom dialog components - text, image and button
				final EditText text=(EditText)dialog.findViewById(R.id.editText1);

				SQLiteDatabase mydb = openOrCreateDatabase("shiveh.db", Context.MODE_PRIVATE,null);
				try
	               {
						Cursor allrows  = mydb.rawQuery("SELECT * FROM shiveh WHERE ID='"+parent+"_"+child+"'", null);
						if(allrows.moveToFirst()){
		   	    	        do{
		   	    	        	exist_comment=true;
		   	    	        	text.setText(allrows.getString(1));
		   	    	        }
		   	    	        while(allrows.moveToNext());
						}
	               }
	               catch (Exception e) {
					// TODO: handle exception
				}
				mydb.close();
				
				
				Button cancel=(Button)dialog.findViewById(R.id.button1);
				cancel.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						drawerLayout.closeDrawers();
					}
				});
				Button ok=(Button)dialog.findViewById(R.id.button2);
				ok.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						SQLiteDatabase mydb = openOrCreateDatabase("shiveh.db", Context.MODE_PRIVATE,null);
						try
			               {
								if(exist_comment){
				   	    	        mydb.execSQL("UPDATE shiveh SET comment='"+text.getText()+"'  WHERE ID='"+parent+"_"+child+"'");
								}
								else
								{
				   	    	     	mydb.execSQL("INSERT INTO shiveh (ID,comment,Fav) VALUES ('"+parent+"_"+child+"','"+text.getText()+"'"+",0)");
								}
			               }
			               catch (Exception e) {
							// TODO: handle exception
						}
						mydb.close();
						
						dialog.dismiss();
						drawerLayout.closeDrawers();
					}
				});
				dialog.show();
			}
		});
		
		
		
		final WebView mWebView = (WebView) findViewById(R.id.webView1);
		final WebSettings settings = mWebView.getSettings();
		settings.setDefaultTextEncodingName("utf-8");                   
		
		
		
		final SeekBar seek=(SeekBar)findViewById(R.id.seekBar1);
		
		seek.setMax(60);
		
		float fs = prefs.getFloat("fontsize", 16);
		seek.setProgress((int)fs);
		

		mWebView.loadData("<style>.title{font-size:"+String.valueOf(seek.getProgress()+2)+"px;}.all{font-size:"+String.valueOf(seek.getProgress())+"px;line-height:"+String.valueOf(seek.getProgress()*2)+"px;}</style>"+str, "text/html; charset=utf-8",null);
		
		
			seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub

				if(seek.getProgress()>=16)
					mWebView.loadData("<style>.title{font-size:"+String.valueOf(seek.getProgress()+2)+"px;}.all{font-size:"+String.valueOf(seek.getProgress())+"px;line-height:"+String.valueOf(seek.getProgress()*2)+"px;}</style>"+str, "text/html; charset=utf-8",null);
				else
					mWebView.loadData("<style>.title{font-size:18px;}.all{font-size:16px;line-height:30px;}</style>"+str, "text/html; charset=utf-8",null);
			}
		});
		
		ImageView img=(ImageView)findViewById(R.id.imageView1);
		img.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				drawerLayout.openDrawer(drawerView);
			}
		});
	}
	
	
	public int ShowFav()
	{
		SQLiteDatabase mydb = openOrCreateDatabase("shiveh.db", Context.MODE_PRIVATE,null);
		int a=0;
		try
           {
				Cursor allrows  = mydb.rawQuery("SELECT * FROM shiveh WHERE ID='"+parent+"_"+child+"'", null);
				if(allrows.moveToFirst()){
   	    	        do{
   	    	        	if(allrows.getString(2)=="0")
   	    	        	{
   	    	        		
   	    	        	}
   	    	        	else
   	    	        	{
   	    	        		
   	    	        		a=1;
   	    	        	}
   	    	        }
   	    	        while(allrows.moveToNext());
				}

           }
           catch (Exception e) {
			// TODO: handle exception
		}
		mydb.close();
		
		return a;
	}
	
	
	void hightLightText(TextView textView, String searchString){
        try{
        
            String withHighLightedText = ((String) textView.getText()).replaceAll(searchString, "<font color='red'>"+searchString)+"</font>";
            textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
            }catch(Exception ex){

            }

    }
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
	
		if(getIntent().getExtras().getString("search")==null)
		{
			finish();
			startActivity(new Intent(Show.this, MainActivity.class));
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
		else
		{
			super.onBackPressed();
		}
	}
}
