package athary.audio.ency;


import info.guardianproject.database.sqlcipher.SQLiteDatabase;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import athary.audio.ency.R;
import athary.audio.ency.Helpers.data.NewDataDbAdapter;

public class DroosActivity extends Activity {

//Define Views
private ExpandableListView exp;

//Define Other Variables
private NewDataDbAdapter mDbHelper; // db adapter
private Cursor mGroupsCursor; 
private Integer[] sheekhnos;
private Integer[] booksnos;

private int BID;
private int SID;

private int Sheekh_Sel, Book_Sel;
public String IND;
public String URL;
public String SEEK;
public String TITLE =  "";
private String indcode;
private SharedPreferences athary;
private SharedPreferences.Editor atharyEditor;
private Spinner spinner2;
private Spinner spinner1;


@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nlists);
		
    		initDB();
    		initViews();

}

private void initDB(){

    athary = getSharedPreferences("athary", 0);

    SQLiteDatabase.loadLibs(this);
	NewDataDbAdapter.PATH = athary.getString("path", "");
  	mDbHelper = NewDataDbAdapter.getInstance(this);
    mDbHelper.open("Athary412Test412");
	mGroupsCursor = mDbHelper.AllSheekhs(); 
	
	Sheekh_Sel = athary.getInt("Sheekh_Sel", 0);
	Book_Sel = athary.getInt("Book_Sel", 0);
}

private void initViews(){
	
	spinner2 = (Spinner) findViewById(R.id.spinnerfield);
	spinner1 = (Spinner) findViewById(R.id.spinnertype);
    exp = (ExpandableListView)findViewById(R.id.list);
    
    
	String [] spinnerdata = new String[mGroupsCursor.getCount()];
	final Integer[] spinnernos = new Integer[mGroupsCursor.getCount()];
	
	mGroupsCursor.moveToFirst();
	for (int i = 0; i < spinnerdata.length; i++) {
		spinnerdata[i] = mGroupsCursor.getString(mGroupsCursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_NAME));
		spinnernos[i] = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID));
		mGroupsCursor.moveToNext();	
	}
	
	FieldSpinnerAdapter typeadapter = new FieldSpinnerAdapter(this, spinnerdata);

	spinner1.setAdapter( typeadapter );
	spinner1.setSelection(Sheekh_Sel);

	spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {


		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
	        Cursor BooksCursor = mDbHelper.BooksBy_SHEEKH_ID(spinnernos[arg2]);
	       	String [] spinnertypes = new String[BooksCursor.getCount()];
	    	sheekhnos = new Integer[BooksCursor.getCount()];
	    	booksnos = new Integer[BooksCursor.getCount()];

			   atharyEditor = athary.edit();
			   atharyEditor.putInt("Sheekh_Sel", arg2);
			   atharyEditor.commit();	

	    	BooksCursor.moveToFirst();
	    	for (int i = 0; i < spinnertypes.length; i++) {
	    		spinnertypes[i] = BooksCursor.getString(BooksCursor.getColumnIndex(NewDataDbAdapter.KEY_BOOK_NAME));
	    		sheekhnos[i] = BooksCursor.getInt(BooksCursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID));
	    		booksnos[i] = BooksCursor.getInt(BooksCursor.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID));
	    		BooksCursor.moveToNext();	
	    	}

	    	FieldSpinnerAdapter spinadapter = new FieldSpinnerAdapter(DroosActivity.this, spinnertypes);
	    	spinner2.setAdapter(spinadapter);
	    	if (Sheekh_Sel == athary.getInt("Sheekh_Sel", 0)) spinner2.setSelection(Book_Sel);
	    	else spinner2.setSelection(0);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

			
		}
	});
	
	spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

		private MyExpandableListAdapter mAdapter;

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
	        Cursor ChaptersCursor = mDbHelper.ChaptersBy_BOOK_GROUP(sheekhnos[arg2], booksnos[arg2]);
	        mAdapter = new MyExpandableListAdapter(ChaptersCursor,DroosActivity.this, R.layout.group_chapters, R.layout.child_chapters, new String[] { NewDataDbAdapter.KEY_TITLE}, new int[] { R.id.ind }, new String[] { NewDataDbAdapter.KEY_FILENAME, NewDataDbAdapter.KEY_TITLE }, new int[] { R.id.code, R.id.ind_child });
	        
			   atharyEditor = athary.edit();
			   atharyEditor.putInt("Book_Sel", arg2);
			   atharyEditor.commit();	

	        exp.setAdapter(mAdapter);
	        if (exp.getCount() == 1) exp.expandGroup(0);
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

			
		}
	});


}

public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {

public MyExpandableListAdapter(Cursor cursor, Context context, int groupLayout, int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom, int[] childrenTo) {super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);}

        @Override
        protected Cursor getChildrenCursor(Cursor groupCursor) {
               Cursor IndexCursor = mDbHelper.ChaptersBy_Title(groupCursor.getString(groupCursor.getColumnIndex(NewDataDbAdapter.KEY_TITLE)), groupCursor.getInt(groupCursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)), groupCursor.getInt(groupCursor.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));
               return IndexCursor;
        }
        public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) { 
                   	
            	final View groupView = super.getGroupView(groupPosition, isExpanded, convertView, parent);

            	TextView txt = (TextView)groupView.findViewById(R.id.ind);
            	txt.setTypeface(IntroActivity.tf,Typeface.NORMAL);
            	txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, IntroActivity.fontsize);

            return groupView; 
        } 
        
        // I needed to process click on click of the button on child item
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
                
	final View rowView = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
	final TextView ind_code = (TextView)rowView.findViewById(R.id.ind_code);

    Cursor cr = getChild(groupPosition, childPosition);
    indcode = cr.getString(cr.getColumnIndex(NewDataDbAdapter.KEY_TITLE)) + "(" + cr.getString(cr.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + ")";

		//    if (checkConnectivity()) {
		//    	Toast.makeText(getApplicationContext(), "تم بدء التحميل", Toast.LENGTH_SHORT).show();
		    	

		   // new DownloadFile().execute(URL2.replaceAll("\\\\" , "/"));
		    	
		//		Intent intent = new Intent(nSheekhs_and_Books_Activity.this, DownloadService.class);  
	//		intent.putExtra("downloadUrl", "http://www.maknoon.com/download/audios/" + URL2.replaceAll("\\\\" , "/"));
		//		nSheekhs_and_Books_Activity.this.startService(intent);

	//	    }else if (!checkConnectivity()) Toast.makeText(getApplicationContext(), "اتصل بالإنترنت أولا!", Toast.LENGTH_SHORT).show();

    
		ind_code.setTypeface(IntroActivity.tf,Typeface.NORMAL);
		ind_code.setTextSize(TypedValue.COMPLEX_UNIT_SP, IntroActivity.fontsize - 1);
		
		ind_code.setText(indcode);

		//Set The Appearance Of Childs
		if (childPosition == 0 && cr.getCount() > 1) {
			ind_code.setBackgroundResource(R.drawable.child_first);

		}
		else if (childPosition == 0 && cr.getCount() == 1) {
			ind_code.setBackgroundResource(R.drawable.child_middle);
		}
		else if (childPosition == cr.getCount() - 1) {
			ind_code.setBackgroundResource(R.drawable.child_last);
		}
		else {
			ind_code.setBackgroundResource(R.drawable.child);
		}
		
		rowView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					
				    Cursor cr2 = getChild(groupPosition, childPosition);

                    Integer CODE = cr2.getInt(cr2.getColumnIndex(NewDataDbAdapter.KEY_CODE));
                    String URL = cr2.getString(cr2.getColumnIndex(NewDataDbAdapter.KEY_PATH)) + "/" + cr2.getString(cr2.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + "." + cr2.getString(cr2.getColumnIndex(NewDataDbAdapter.KEY_FILETYPE)); 

 		    	   SharedPreferences athary = getSharedPreferences("athary", 0);
		  		   SharedPreferences.Editor editor = athary.edit();
		  		   
		  		   editor.putInt("CODE", CODE);
		  		   editor.putString("TITLE", spinner1.getSelectedItem().toString() + " - " + spinner2.getSelectedItem().toString() + " " + ind_code.getText());
		  		   editor.putString("URL", URL);
		  		   editor.putInt("BID", BID);
		  		   editor.putInt("SID", SID);
		  		   editor.putInt("OFFSET", 0);
		  		   editor.putInt("DURATION", -1);
		  		   editor.putInt("TYPE", 1);
		  		   editor.putString("TXT", "");
		  		   editor.putString("TAF", "");

		  		   //Commit the edits!
		  		   editor.commit();
		  		   finish();
		  		   if (IntroActivity.tabHost != null) {
			  			IntroActivity.newmedia = true;
		  			   IntroActivity.tabHost.setCurrentTab(1);
		  		   }

				}
			});
            	
            return rowView;
    }

}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	
	}



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

}

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

class FieldSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
    String[] values;
    Context context;

    public FieldSpinnerAdapter(Context context, String[] values) {
        this.context = context;
        this.values = values;
    }

    @Override
    public int getCount() {
        return values.length;
    }

    @Override
    public Object getItem(int position) {
        return values[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        if (v == null) {
           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           v = vi.inflate(R.layout.txt_spinner, null);
        } 
		TextView tv=(TextView) v.findViewById(R.id.ind_child);
		//tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		tv.setText(values[position]);
		
		return v;  

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        if (v == null) {
           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           v = vi.inflate(R.layout.txt_spinner_dropdown, null);
        } 
		TextView tv=(TextView) v.findViewById(R.id.ind_child);
		//tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		tv.setBackgroundResource(R.drawable.custom_style_nocorners);
		tv.setTextColor(Color.argb(255, 134, 121, 81));

		tv.setText(values[position]);

		return v;  

    }
}

