package athary.audio.ency;
 
import info.guardianproject.database.sqlcipher.SQLiteDatabase;
import io.vov.utils.StringUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import athary.audio.ency.R;
import athary.audio.ency.Helpers.data.NewDataDbAdapter;
import athary.audio.ency.Helpers.data.IconContextMenu;
import athary.audio.ency.Helpers.main.Utilities;
import athary.audio.ency.Helpers.search.CustomAdapter;
import athary.audio.ency.Helpers.search.RowData;
 
public class Selected_Class_Activity extends Activity {
	
	//Define Views
	private TextView txt_result;
	private Button nextresult;
	private Button prevresult;
	private ListView ls2;
	private ProgressBar progressBar;
	private TextView TextView02;

	//Define Other Variables
	private final int CONTEXT_MENU_ID = 1;
	private IconContextMenu iconContextMenu = null;
	private final int MENU_ITEM_1_ACTION = 1;
	private final int MENU_ITEM_2_ACTION = 2;
	private final int MENU_ITEM_3_ACTION = 3;
	private final int MENU_ITEM_4_ACTION = 4;
	private RowData row;
	private ArrayList<RowData> ROWS = new ArrayList<RowData>();
	private int count = 0;
	private int istart;
	private int iend;
	private int CODE;
	private String SHEEKH, BOOK, CHAPTER;
	private int SEQ;
	private String TITLE;
	private String URL;
	private int OFFSET;
	private int DURATION;
	private String TXT;
	private String TAF;
	private String link;
	private Utilities utils;
	private NewDataDbAdapter dbHelper;
	private SharedPreferences athary;
	private CustomAdapter lvAdapter;
	private int CAT_ID;
	private static int RESULT_PER_PAGE = 50;

	 @Override
	 public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.favorites);
	  
		Intializations();
		itializecontextmenu();
		initViews();
		Appearance();
		setListeners();
		Start_Search(0, RESULT_PER_PAGE);

	 }

	private void Intializations() {

	    SQLiteDatabase.loadLibs(this);
	    athary = getSharedPreferences("athary", 0);
	  	dbHelper = NewDataDbAdapter.getInstance(this);
	    dbHelper.open("Athary412Test412");
		  utils = new Utilities();
		  link = athary.getString("link", "http://www.maknoon.com/download/audios/");
		  lvAdapter =  new CustomAdapter(this, ROWS);
		  CAT_ID = getIntent().getIntExtra("CATID",0);
	}

	private void itializecontextmenu(){
		
	    Resources res = getResources();
	      
	    //init the menu
	    iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
	    iconContextMenu.addItem(res, "تشغيل المادة الصوتية", MENU_ITEM_1_ACTION);
	    iconContextMenu.addItem(res, "إضافة إلى المفضلة", MENU_ITEM_2_ACTION);
	    iconContextMenu.addItem(res, "مشاركة الفهرس فقط", MENU_ITEM_3_ACTION);
	    iconContextMenu.addItem(res, "مشاركة الفهرس والتفريغ", MENU_ITEM_4_ACTION);
	    
	}

	private void initViews() {

		  TextView02 = (TextView) findViewById(R.id.TextView02);
		  nextresult = (Button) findViewById(R.id.nextresult);
		  prevresult = (Button) findViewById(R.id.prevresult);
		  ls2 = (ListView) findViewById(R.id.listView1);
		  progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
		  txt_result = (TextView) findViewById(R.id.txt_result);

	}

	private void Appearance() {
		  TextView02.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		  TextView02.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		  txt_result.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		  txt_result.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		  nextresult.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		  nextresult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		  prevresult.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		  prevresult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);

		  progressBar.setProgress(0);
		
	}

	private void setListeners() {

		  nextresult.setOnClickListener(new View.OnClickListener() {
				
			@Override
			public void onClick(View v) {
				Start_Search(istart + RESULT_PER_PAGE, iend + RESULT_PER_PAGE);
			}
		});
		  
		  prevresult.setOnClickListener(new View.OnClickListener() {
				
			@Override
			public void onClick(View v) {
				Start_Search(istart - RESULT_PER_PAGE, iend - RESULT_PER_PAGE);
			}
		});
		  
		     ls2.setOnItemClickListener(new OnItemClickListener() 
		     {

				public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
		     	{
					
			 		CODE = ROWS.get(arg2).getCODE();
			 		SEQ = ROWS.get(arg2).getSEQ();
			 		SHEEKH = ROWS.get(arg2).getSHEEKH();
			 		BOOK = ROWS.get(arg2).getBOOKNAME();
			 		CHAPTER = ROWS.get(arg2).getCHAPTER();
			 		OFFSET = ROWS.get(arg2).getOFFSET();
			 		DURATION = ROWS.get(arg2).getDURATION();
			 		URL = ROWS.get(arg2).getURL();
			 		TITLE = SHEEKH + "\n" + BOOK + "\n" + CHAPTER + "\n" + "بداية المقطع: " + utils.milliSecondsToTimer(OFFSET) + "\n" + "المدة: " + utils.milliSecondsToTimer(DURATION) + "\n" + "الوصلة: " + Pasre_URL(URL);
				 	TXT = ROWS.get(arg2).getTXT();
				 	TAF =  ROWS.get(arg2).getTAF();
				 		
			        showDialog(CONTEXT_MENU_ID);

					} 		
		 	});
		     
			    //set onclick listener for context menu
			    iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			        
					@Override
					public void onClick(int menuId) {
						
						switch(menuId) {
						
						case MENU_ITEM_1_ACTION:
							
				    	   SharedPreferences athary = getSharedPreferences("athary", 0);
				  		   SharedPreferences.Editor editor = athary.edit();
				  		   
				  		   editor.putInt("CODE", CODE);
				  		   editor.putString("TITLE", SHEEKH + " - " + BOOK + " - " + CHAPTER);
				  		   editor.putString("URL", URL);
				  		   editor.putInt("OFFSET", OFFSET);
				  		   editor.putInt("DURATION", DURATION);
				  		   editor.putInt("TYPE", 2);
				  		   editor.putString("TXT", TXT);
				  		   editor.putString("TAF", TAF);

				  		   //Commit the edits!
				  		 editor.commit();
				  		 IntroActivity.mytxt = Html.fromHtml(TXT) + "\n\n" + TAF;
				  		 IntroActivity.stime = "التوقيت: " + StringUtils.generateTime(OFFSET);
				  		 IntroActivity.etime = "المدة: " + StringUtils.generateTime(DURATION);
				  		 
				  		 if (IntroActivity.tabHost != null) {
				  			IntroActivity.newmedia = true;
				  			IntroActivity.tabHost.setCurrentTab(0);
				  		 }
				  		 //finish();
							break;
							
						case MENU_ITEM_2_ACTION:

							dbHelper.updatebyFAV(CODE, SEQ, 1);
							Toast.makeText(getApplicationContext(), "تم إضافة الفهرس إلى المفضلة", Toast.LENGTH_LONG).show();

							break;

						case MENU_ITEM_3_ACTION:
							Intent sendIntent_IND = new Intent();
							sendIntent_IND.setAction(Intent.ACTION_SEND);
							sendIntent_IND.putExtra(Intent.EXTRA_TEXT, TXT + "\n" + "المصدر: " + "\n" + TITLE);
							sendIntent_IND.setType("text/plain");
							startActivity(sendIntent_IND);
							
							break;
							
						case MENU_ITEM_4_ACTION:
							Intent sendIntent_TAF = new Intent();
							sendIntent_TAF.setAction(Intent.ACTION_SEND);
							sendIntent_TAF.putExtra(Intent.EXTRA_TEXT, TXT + "\n" + TAF + "\n" + "المصدر: " + "\n" + TITLE);
							sendIntent_TAF.setType("text/plain");
							startActivity(sendIntent_TAF);
							
						break;
							
						}
					}
				});
	}

	 private void Start_Search(Integer start, Integer end){
			count = 0;
		    istart = start;
		    iend = end;
		    new BackgroundAsyncTask().execute("0");  
	 }

	 private void listclicks(){
		  lvAdapter.notifyDataSetChanged();
	 	  ls2.setAdapter(lvAdapter);
	 	  
	}

	 private String Pasre_URL(String URL){
			try {
				URL url;
		        URL = URL.replaceAll("\\\\" , "/");
				url = new URL(link + URL);
					URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
					url = uri.toURL();
					URL = url.toString();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}	
			return URL;
		}
	 
	 public class BackgroundAsyncTask extends AsyncTask<String, Void, Void> {
		 ArrayList<RowData> ROWS_NEW = new ArrayList<RowData>();
		 Cursor class_cursor;
		 
		private int offset;
		private int duration;
		private String Line;
		private String tafreeg;
		private int fav;
		
		private Cursor cont;
		private Cursor sh;
		private Cursor book;
		private Cursor chp;
	  @Override
	  protected void onPostExecute(Void unused) {
		  
		  if (ROWS_NEW.isEmpty()) {
		  		ls2.setEnabled(false);
		  		progressBar.setVisibility(View.GONE);
		  		}
		  ROWS.clear();
		  ROWS.addAll(ROWS_NEW);
		  progressBar.setVisibility(View.GONE);
		  
		  if (iend > 50 && iend < class_cursor.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.VISIBLE);
			  
		  }else if(iend <= 50 && iend == class_cursor.getCount()){
			  nextresult.setVisibility(View.INVISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
			  
		  }else if(iend <= 50 && iend < class_cursor.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
		  }
		  else if(iend > 50 && iend == class_cursor.getCount()){
			  nextresult.setVisibility(View.INVISIBLE);
			  prevresult.setVisibility(View.VISIBLE);
		  }
			  
		  BackgroundAsyncTask.this.cancel(true);
		  
		  
		 if (count == 0) {
			 count++;

			 listclicks();
		 }
		 nextresult.setEnabled(true);
		 prevresult.setEnabled(true);
		 ls2.setVisibility(View.VISIBLE);
		 if (class_cursor.getCount() > 0) txt_result.setText(" الفهارس من" + String.valueOf(istart + 1) + " إلى " + iend + "\n" + "مجموع الفهارس: " + class_cursor.getCount());
		 else txt_result.setText("لا توجد فهارس لهذا الصنف!");

	  }

	  @Override
	  protected void onPreExecute() {
		  
		  progressBar.setProgress(0);
		  progressBar.setMax(100);
		  ROWS_NEW.clear();
		  ls2.setAdapter(null);
		  ls2.setVisibility(View.GONE);
		  ls2.setEnabled(true);
		  progressBar.setVisibility(View.VISIBLE);
		  //ls2.setVisibility(View.INVISIBLE);
		  
		  nextresult.setEnabled(false);
		  prevresult.setEnabled(false);
	  }

	  @Override
	  protected Void doInBackground(String... aurl) {

		  class_cursor   = dbHelper.ContentCatBy_CATEGORY_ID(CAT_ID);
			 
			 if (class_cursor != null) class_cursor.moveToPosition(istart);
			 
		    for (int i = istart; i < iend; i++) {
		    	if (class_cursor.getPosition() < class_cursor.getCount() && class_cursor.getPosition() >= 0){
				  cont = dbHelper.ContentsBy_CAT(class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_CODE)), class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_SEQ)));

				  sh = dbHelper.SheekhBy_SHEEKH_ID(class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));	 
				  book = dbHelper.BooksBy_BOOK_ID(class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));	
			 	  chp = dbHelper.ChaptersBy_CODE(class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_CODE)));

				 SHEEKH = ""; 
				 BOOK = "";
				 URL = "";
				 CHAPTER = "";
				 offset = 0;
				 duration = 0;
				 Line = "";
				 tafreeg = "";
				 fav =0;
				 if (sh.getCount() > 0) {
					 SHEEKH = sh.getString(sh.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_NAME));
				 }
				 if (book.getCount() > 0) {
					 BOOK = book.getString(book.getColumnIndex(NewDataDbAdapter.KEY_BOOK_NAME));
				 }
				 if (chp.getCount() > 0){
					 URL = chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_PATH)) + "/" + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + "." + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILETYPE));
					 CHAPTER = chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_TITLE)) + "(" + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + ")";
				 }
				 if (cont.getCount() > 0){
					 offset = cont.getInt(cont.getColumnIndex(NewDataDbAdapter.KEY_OFFSET));
					 duration = cont.getInt(cont.getColumnIndex(NewDataDbAdapter.KEY_DURATION));
					 Line = cont.getString(cont.getColumnIndex(NewDataDbAdapter.KEY_LINE));
					 tafreeg = cont.getString(cont.getColumnIndex(NewDataDbAdapter.KEY_TAFREEG));
					 fav = cont.getInt(cont.getColumnIndex(NewDataDbAdapter.KEY_FAV));
				 }

				 	row = new RowData(
				 			i,
				 			class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_CODE)),
				 			class_cursor.getInt(class_cursor.getColumnIndex(NewDataDbAdapter.KEY_SEQ)),
				 			SHEEKH,
				 			BOOK,
				 			CHAPTER,
				 			offset,
				 			duration,
				 			Line,
				 			tafreeg,
				 			URL,
				 			fav,""
				 			);
					ROWS_NEW.add(row);
				
					class_cursor.moveToNext();
		    	}
		    	
			    }
	    	iend = class_cursor.getPosition();
	    	

	   return null;
	  }

	  @Override
	  protected void onProgressUpdate(Void... values) {
	  }

	 }

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == CONTEXT_MENU_ID) {
			return iconContextMenu.createMenu("خيارات الفهرس");
		}
		return super.onCreateDialog(id);
	}

	  @Override
	  protected void onResume() {
	 	 super.onResume();
	  }
	  
	  @Override
	  protected void onDestroy() {
	  	super.onDestroy();
	  }
}  




	