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 Favorite_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 final int MENU_ITEM_5_ACTION = 5;
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 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() {

	athary = getSharedPreferences("athary", 0); 
    SQLiteDatabase.loadLibs(this);
	NewDataDbAdapter.PATH = athary.getString("path", "");;
  	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);

}

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_5_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);
				  		 }

						break;
						
					case MENU_ITEM_2_ACTION:

						dbHelper.updatebyFAV(CODE, SEQ, 0);
						Toast.makeText(getApplicationContext(), "تم حذف الفهرس من المفضلة", Toast.LENGTH_LONG).show();
						count = 0;
				        new BackgroundAsyncTask().execute("0");

						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;
						
					case MENU_ITEM_5_ACTION:

						dbHelper.updatebyAllFAV();
						Toast.makeText(getApplicationContext(), "تم حذف كل الفهارس من المفضلة", Toast.LENGTH_LONG).show();
						count = 0;
				        new BackgroundAsyncTask().execute("0");

						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 cur;
		 
	  @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 < cur.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.VISIBLE);
			  
		  }else if(iend <= 50 && iend == cur.getCount()){
			  nextresult.setVisibility(View.INVISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
			  
		  }else if(iend <= 50 && iend < cur.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
		  }
		  else if(iend > 50 && iend == cur.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 (cur.getCount() > 0) txt_result.setText(" الفهارس المفضلة من" + String.valueOf(istart + 1) + " إلى " + iend + "\n" + "مجموع الفهارس: " + cur.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) {

			 cur   = dbHelper.ContentsBy_FAV(1);

			 cur.moveToPosition(istart);
			 
		    for (int i = istart; i < iend; i++) {
		    	if (cur.getPosition() < cur.getCount() && cur.getPosition() >= 0){
				 Cursor sh = dbHelper.SheekhBy_SHEEKH_ID(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));	 
				 Cursor book = dbHelper.BooksBy_BOOK_ID(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));	
			 	 Cursor chp = dbHelper.ChaptersBy_CODE(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_CODE)));

				 sh.moveToFirst();
				 book.moveToFirst();
				 chp.moveToFirst();
				 
				 SHEEKH = ""; 
				 BOOK = "";
				 URL = "";
				 CHAPTER = "";
				 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)) + ")";
				 }

				 	row = new RowData(
				 			i,
				 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_CODE)),
				 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_SEQ)),
				 			SHEEKH,
				 			BOOK,
				 			CHAPTER,
				 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_OFFSET)),
				 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_DURATION)),
				 			cur.getString(cur.getColumnIndex(NewDataDbAdapter.KEY_LINE)),
				 			cur.getString(cur.getColumnIndex(NewDataDbAdapter.KEY_TAFREEG)),
				 			URL,
				 			0,""
				 			);
					ROWS_NEW.add(row);
				
				cur.moveToNext();
		    	}
		    	
			    }
	    	iend = cur.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();
	 }
}  

