package athary.audio.ency;

import info.guardianproject.database.sqlcipher.SQLiteDatabase;
import io.vov.utils.StringUtils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import athary.audio.ency.Helpers.data.CSV_Reader;
import athary.audio.ency.Helpers.data.NewDataDbAdapter;
import athary.audio.ency.Helpers.main.FileChooser;
import athary.audio.ency.Helpers.main.Utilities;

public class IntroActivity extends TabActivity implements OnSeekBarChangeListener{
	
	//Define Views
	private TextView mCurrentTime;
	private TextView mEndTime;
	private TextView TitleLabel;
	private SeekBar songProgressBar;
	private ImageButton btnPlay;
	private ImageButton downbtn;
	private ProgressBar downprog;
	private LinearLayout downlay;
	
	//Public Variables
	public static Typeface tf;
	public static float fontsize;
	
	//Define Other Variables
	public static NewDataDbAdapter mDbHelper;
	private Cursor cursor;
	private String URL, URLFORPATH, TITLE, Save_Path, TXT, TAF, link, path, current_ver, file;
	public static String mytxt,stime,etime;
	public static int fav;
	public static int seq;
	public static int CODE;
	public static int viewindex;
	private int linkNo;
	
	public static final String BROADCAST_SEEKBAR = "athary.audio.ency.sendseekbar";
	private int DURATION, PlayStop, index, oldposition, firsttime, totalDuration, currentDuration, songEnded, seekMax;
	private static final int DIALOG_PROGRESS = 1;
	public static int OFFSET;
	private long max_sheekh_id, max_code;
	private String[] ids = null;
	private int[] OFFSETS = null;
	private int[] DURATIONS = null;
	public static int[] FAVS = null;
	private int[] SEQS = null;

	private boolean playserv = false;
	private boolean withindices = false;
	private boolean enable = false;
	public static boolean go = true;
	boolean mBufferBroadcastIsRegistered;
	boolean mBroadcastIsRegistered;
	private boolean isOnline;
	public static boolean newmedia = false;
	public static boolean seechanged = false;
	public static boolean isplaying = false;
	private boolean boolMusicPlaying = false;
	
	public static String txt_for_shrae = "";
	public static String taf_for_shrae = "";

	private Dialog dialogdown = null;
	private File f;
	private ProgressDialog moProgressDialog = null;
	private ProgressDialog pdBuff = null;
	private Utilities utils;
	private java.net.URL url;
	Intent intent, serviceIntent;
	TelephonyManager telephonyManager;
	PhoneStateListener listener;
	private SharedPreferences athary;
	public static TabHost tabHost;
	private int DATABASE_VERSION = 2;
	private final Handler handler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nmediacontroller);
        initDB();
	}
	
	private void initDB() {
		athary = getSharedPreferences("athary", 0);
		path = athary.getString("path", "");
		checkfile();
		}

	private void filldata(){

        try {
            path = athary.getString("path", "");
	        SQLiteDatabase.loadLibs(this);
	    	NewDataDbAdapter.PATH = path;
	      	mDbHelper = NewDataDbAdapter.getInstance(this);
		    mDbHelper.open("Athary412Test412");
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "الملف المحدد غير صحيح حمل قاعدة البيانات من جديد او اختر ملف آخر", Toast.LENGTH_LONG).show();
			path = "";
			checkfile();
		}

    
		try {

			if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this))	return;
			
			serviceIntent = new Intent(this, PlayService.class);
			intent = new Intent(BROADCAST_SEEKBAR);

	        initializations();
			update();
			setupHandler();
		} catch (Exception e) {e.printStackTrace();Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();}

	}
	
	private void initializations() {
		utils = new Utilities();
		
        int FontSize = athary.getInt("FontSize", 1);
		fontsize = 16 + FontSize;
		
        int FontType = athary.getInt("FontType", 3);
	    switch (FontType) {
		case 1: {tf = Typeface.DEFAULT; break;}
		case 2: {tf = Typeface.createFromAsset(getAssets(), "font1.ttf"); break;}
		case 3: {tf = Typeface.createFromAsset(getAssets(), "font2.ttf"); break;}
		case 4: {tf = Typeface.createFromAsset(getAssets(), "font3.ttf"); break;}
		}

		linkNo = athary.getInt("linkNo", 1);
		  if (linkNo == 3) {
	   	   	   linkNo = 1;
	   	   	   link = "http://www.maknoon.com/download/audios/";
	   	   	   SharedPreferences.Editor atharyEditor = athary.edit();
			   atharyEditor.putString("link", "http://www.maknoon.com/download/audios/");
			   atharyEditor.putInt("linkNo", 1);
			   atharyEditor.commit();	
		  }

	    initViews(); 
		inittabs();
		preptmedia();
		setListeners();

	}

	private void initViews() {
		
		downbtn = (ImageButton) findViewById(R.id.down_btn);
		downprog = (ProgressBar)findViewById(R.id.down_prog);
		downprog.setProgress(0);
		downprog.setMax(100);
		downlay = (LinearLayout)findViewById(R.id.downlay);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		TitleLabel = (TextView) findViewById(R.id.scroller);
		mCurrentTime = (TextView) findViewById(R.id.songCurrentDurationLabel);
		mEndTime = (TextView) findViewById(R.id.songTotalDurationLabel);
		
		int type = Typeface.NORMAL;
		Typeface tf = IntroActivity.tf; 
		//Typeface tfdefault = Typeface.createFromAsset(getAssets(), "font2.ttf");
		float fontsize = IntroActivity.fontsize;
		mCurrentTime.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontsize);
		mCurrentTime.setTypeface(Typeface.DEFAULT,type);		
		mEndTime.setTypeface(Typeface.DEFAULT,type);
		mEndTime.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontsize);
		TitleLabel.setTypeface(tf, type);
		TitleLabel.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontsize -1);

		}
	
	private void inittabs() {tabHost = getTabHost(); View tabview = createTabView(tabHost.getContext(), "الحالي"); TabSpec current = tabHost.newTabSpec("1"); current.setIndicator(tabview); Intent currentIntent = new Intent(this, NowPlayingActivity.class); current.setContent(currentIntent); View tabview2 = createTabView(tabHost.getContext(), "الفهارس"); TabSpec indices = tabHost.newTabSpec("2"); indices.setIndicator(tabview2); Intent indicesIntent = new Intent(this, PlaylistActivity.class); indices.setContent(indicesIntent); View tabview3 = createTabView(tabHost.getContext(), "القائمة"); TabSpec main = tabHost.newTabSpec("3"); main.setIndicator(tabview3); Intent mainIntent = new Intent(this, MenuActivity.class); main.setContent(mainIntent); tabHost.addTab(current); tabHost.addTab(indices); tabHost.addTab(main); tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider); tabHost.setCurrentTab(0); TextView txtView=(TextView) findViewById(R.id.scroller); txtView.setSelected(true); tabHost.setOnTabChangedListener(new OnTabChangeListener() {private int i=0; @Override public void onTabChanged(String tabId) {if (tabId.equals("3")) {tabHost.setCurrentTab(i);} i = tabHost.getCurrentTab();}});}

	private void setListeners() {
		btnPlay.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View arg0) {
		if (!isplaying) {
			newmedia = true;
		}
		buttonPlayStopClick();
		}
		});
		
		downbtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				if (Save_Path.equals("")) {
					
					dialogdown = new Dialog(IntroActivity.this);
					dialogdown.setContentView(R.layout.download_popup);
					dialogdown.setTitle("مسار الصوتيات المحملة");
					Button btn_send = (Button)dialogdown.findViewById(R.id.btn_send);
					Button btn_cancel = (Button)dialogdown.findViewById(R.id.btn_cancel);
		
					btn_send.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View arg0) {

							Intent i = new Intent(getApplicationContext(), FileChooser.class);
							i.putExtra("FLAG", "DOWNLOAD");
							startActivityForResult(i, 0);
						}
					});
					
					btn_cancel.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View arg0) {
							dialogdown.dismiss();						
						}
					});
					
					dialogdown.show();
				}
					else{
				Intent intent2 = new Intent(IntroActivity.this, DownloadService.class);
				intent2.putExtra("url", URL);
				intent2.putExtra("save_place", Save_Path + URLFORPATH.replaceAll("\\\\" , "/"));
				intent2.putExtra("receiver", new DownloadReceiver(new Handler()));
				startService(intent2);
					}
			}
		});
		songProgressBar.setOnSeekBarChangeListener(this);
		}
	
	private void preptmedia() {
		firsttime = 1;
		songEnded = 0;
		file = "";

	    link = athary.getString("link", "http://www.maknoon.com/download/audios/");    
		Save_Path = athary.getString("SAVE", "");           
		CODE = athary.getInt("CODE", 0);         
		TITLE = athary.getString("TITLE", "");
		URL = athary.getString("URL", "");
		OFFSET = athary.getInt("OFFSET", 0);
		DURATION = athary.getInt("DURATION", 0);
		TXT = athary.getString("TXT", "");
		TAF = athary.getString("TAF", "");

		URLFORPATH = URL;
		oldposition = OFFSET;

  				stime = "التوقيت: " + StringUtils.generateTime(OFFSET);
  				if (DURATION == -1) etime = "المدة: " + "غير محدد";
  				else if (DURATION == 0) etime = "";
  				else etime = "المدة: " + StringUtils.generateTime(DURATION);
			
 			 TitleLabel.setText(TITLE);
 			 mytxt = Html.fromHtml(TXT) + "\n\n" + TAF;
 			 mEndTime.setText(StringUtils.generateTime(0));
 			 mCurrentTime.setText(StringUtils.generateTime(0));

  		initURL();
		initIndecies();
		checklibrary();

	}
	
	public void checklibrary() {
		if (CODE == 0) {
			btnPlay.setEnabled(false);
			downbtn.setEnabled(false);
		}else {
			btnPlay.setEnabled(true);
			downbtn.setEnabled(true);
		}
		 File downloaded_files = new File(Save_Path + URLFORPATH.replaceAll("\\\\" , "/"));
		 if (downloaded_files.isFile()) downbtn.setImageResource(R.drawable.nsave_ok);
		 else downbtn.setImageResource(R.drawable.nsave);
	} 

	private void initURL() {
		URL = URL.replaceAll("\\\\" , "/");
			try {
				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();
				}			
	}
	
	private void initIndecies() {
  		    cursor = mDbHelper.ContentsBy_CODE(CODE);
  		    if (cursor.getCount() > 0) {
  		  	withindices = true;
  				ids = new String[cursor.getCount()];
  				OFFSETS = new int[cursor.getCount()];
  				DURATIONS = new int[cursor.getCount()];
  				FAVS = new int[cursor.getCount()];
  				SEQS = new int[cursor.getCount()];
  				cursor.moveToFirst();
  				
  				for(int i = 0;i < cursor.getCount(); i++){
  					ids[i] = cursor.getString(cursor.getColumnIndex(NewDataDbAdapter.KEY_LINE)) + "\n" + cursor.getString(cursor.getColumnIndex(NewDataDbAdapter.KEY_TAFREEG));
  					OFFSETS[i] = cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_OFFSET));
  					DURATIONS[i] = cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_DURATION));
  					FAVS[i] = cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_FAV));
  					SEQS[i] = cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SEQ));
  					cursor.moveToNext();
  				}
  			}
  		}
	
	private void update(){
	  	max_sheekh_id = mDbHelper.getMax_Sheekh_Id();
	  	max_code = mDbHelper.getMax_Code();		
	  	if (mDbHelper.isOpen()) {
	  		mDbHelper.checkvertable();
  			Cursor c = mDbHelper.Allver();
  			if (c.getCount() == 0) {
  				mDbHelper.newver(1);
  				current_ver = "1";
  			}
  			else {
  				c.moveToLast();
  	  			current_ver = c.getString(0);
  			}
  		}
		  	if (checkConnectivity() && current_ver.equals("1")) {
		  		file  = "update" + current_ver + ".zip";
		  		new BackgroundAsyncTask().execute(file);
		  	}
	}	
	
	
	private void updateUI(Intent serviceIntent) {
		String counter = serviceIntent.getStringExtra("counter");
		String mediamax = serviceIntent.getStringExtra("mediamax");
		String strSongEnded = serviceIntent.getStringExtra("song_ended");
		int seekProgress = Integer.parseInt(counter);
		seekMax = Integer.parseInt(mediamax);
		songEnded = Integer.parseInt(strSongEnded);
		songProgressBar.setMax(seekMax);
		songProgressBar.setProgress(seekProgress);
		if (songEnded == 1) {
			btnPlay.setImageResource(R.drawable.btn_pause);
		}
		   	currentDuration = seekProgress;
			totalDuration = seekMax;
	
			mEndTime.setText(utils.milliSecondsToTimer(totalDuration));
		   
			if (currentDuration < oldposition && firsttime == 1 && PlayStop ==1) currentDuration = oldposition;
			if (currentDuration < 0L) mCurrentTime.setText(utils.milliSecondsToTimer(0));
			else mCurrentTime.setText(utils.milliSecondsToTimer(currentDuration));
			
			 if (withindices) updateindices();
			 
			 if (oldposition != OFFSET){
				firsttime = 1;
				go = true;
				oldposition = OFFSET;
			 }
			 
			 if (go) {
					intent.putExtra("stat", 3);
					intent.putExtra("seekpos", OFFSET);
					intent.putExtra("seekbol", true);
					sendBroadcast(intent);
					go = false;
			 }

	}
	
	private void buttonPlayStopClick() {
		
		if (!boolMusicPlaying) {
			btnPlay.setImageResource(R.drawable.btn_pause);
			boolMusicPlaying = true;
			intent.putExtra("stat", 2);
		} else {
			if (boolMusicPlaying) {
				btnPlay.setImageResource(R.drawable.btn_play);
				boolMusicPlaying = false;
				intent.putExtra("stat", 1);
			}
		}
		intent.putExtra("seekbol", false);
		sendBroadcast(intent);
	}
	
	
	private void playAudio() {
	
		stopMyPlayService();
		boolMusicPlaying = true;
		btnPlay.setImageResource(R.drawable.btn_pause);
		playserv = true;
		
		File h = new File(Save_Path + URLFORPATH.replaceAll("\\\\" , "/")); 
		if(h.isFile()) serviceIntent.putExtra("sentAudioLink", Save_Path + URLFORPATH.replaceAll("\\\\" , "/"));
		else {
			isOnline = checkConnectivity();
			if (isOnline) {
				serviceIntent.putExtra("sentAudioLink", URL);
				//if (myduration > 0) totalDuration = myduration;
				//serviceIntent.putExtra("seek", OFFSET);
				//else if (myduration == -1) totalDuration = mp.getDuration() - OFFSET;
				//else totalDuration = mp.getDuration();
			}
			else if (!isOnline) {
				isplaying = false;
				playserv = false;
				serviceIntent.putExtra("sentAudioLink", "");
			}
		}
		if (playserv){
		try {
			serviceIntent.putExtra("title", TitleLabel.getText().toString());
			startService(serviceIntent);
			registerReceiver(broadcastReceiver, new IntentFilter(PlayService.BROADCAST_ACTION));
			mBroadcastIsRegistered = true;
		} catch (Exception e) {
			e.printStackTrace();Toast.makeText(this,"لا يمكن تشغيل المادة الصوتية!", Toast.LENGTH_LONG).show();
			}
		}
	}

	private void showPD(Intent bufferIntent) {
		String bufferValue = bufferIntent.getStringExtra("buffering");
		int bufferIntValue = Integer.parseInt(bufferValue);
		switch (bufferIntValue) {
		case 0: if (pdBuff != null) {pdBuff.dismiss();}	break;
		case 1:	BufferDialogue(); break;
		case 2: buttonPlayStopClick(); break;
	}
}

	private void setupHandler() {
		handler.removeCallbacks(sendUpdatesToUI);
		handler.postDelayed(sendUpdatesToUI, 10); // 1 second
	}

	private Runnable sendUpdatesToUI = new Runnable() {

		public void run() {

			if (newmedia) {
				newmedia = false;
				preptmedia();
				playAudio();
				isplaying = true;
				go = true;
			}
 
			handler.postDelayed(this, 10); // 2 seconds

		}
	};

	@Override
	public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
	
		 if (fromUser) {
			 	firsttime = 0;
			 	//OFFSET = progress;
				mCurrentTime.setText(utils.milliSecondsToTimer(progress));
		 }
	}

	private void updateindices(){
		//if (DURATIONS[0] == -1L) DURATIONS[0] = mp.getDuration();
		index = 0; viewindex = 0;
		while (currentDuration >= OFFSETS[index] && viewindex < OFFSETS.length - 1){
			viewindex = index;
			if (index < OFFSETS.length - 1) index++;
			else if (index == OFFSETS.length - 1) viewindex = OFFSETS.length - 1; 
			enable  = true;
		}
		if (enable == true){
			stime = "التوقيت: " + utils.milliSecondsToTimer(OFFSETS[viewindex]); 
			if (DURATIONS[viewindex] == -1) etime = "المدة: " + utils.milliSecondsToTimer(Long.valueOf(seekMax - OFFSETS[viewindex]));
			else etime = "المدة: " + utils.milliSecondsToTimer(DURATIONS[viewindex]);
			mytxt = ids[viewindex];
			fav = FAVS[viewindex];
			seq = SEQS[viewindex];
			txt_for_shrae = mytxt + "\n" + "المصدر: " + TitleLabel.getText().toString() + "\n" + "الوصلة: " + "http://www.maknoon.com/download/audios/" + URLFORPATH.replaceAll("\\\\" , "/").replaceAll(" ", "%20");
			
			
			PlayStop = athary.getInt("PlayStop", 1);           
			if (oldposition < OFFSETS[viewindex] && PlayStop == 2)
			{
				oldposition = OFFSETS[viewindex];
				OFFSET = OFFSETS[viewindex];
				btnPlay.setImageResource(R.drawable.btn_play);
				boolMusicPlaying = false;
				intent.putExtra("stat", 1);
				intent.putExtra("seekbol", false);
				sendBroadcast(intent);
			}
			enable = false;
		}
	}

	private class DownloadReceiver extends ResultReceiver{
	    public DownloadReceiver(Handler handler) {
	        super(handler);
	    }

	    @Override
	    protected void onReceiveResult(int resultCode, Bundle resultData) {
	        super.onReceiveResult(resultCode, resultData);

	        if (resultCode == DownloadService.UPDATE_PROGRESS) {
	        	if (downlay.getVisibility() == View.GONE) downlay.setVisibility(View.VISIBLE);
	            int progress = resultData.getInt("progress");
	            
	            downprog.setProgress(progress);
	            
	            if (progress == 100) {
	            	downprog.setProgress(0);
	            	downlay.setVisibility(View.GONE);
	            	checklibrary();
	            }
	        }
	    }
	}

	@Override public void onStartTrackingTouch(SeekBar seekBar) {intent.putExtra("stat", 1); sendBroadcast(intent);}
	@Override public void onStopTrackingTouch(SeekBar seekBar) {intent.putExtra("stat", 2); intent.putExtra("seekpos", seekBar.getProgress()); intent.putExtra("seekbol", true); sendBroadcast(intent);}
	@Override public void onBackPressed() {finish(); super.onBackPressed();}
	@Override protected void onDestroy() {stopMyPlayService(); handler.removeCallbacks(sendUpdatesToUI); super.onDestroy();}
	private void checkfile() {f = new File(path); if(f.isFile() && f.length() > 1000000) {filldata();} else {f.delete(); Intent i = new Intent(getApplicationContext(), athary.audio.ency.Wizard.class); startActivityForResult(i, 0);}}	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 1){
			finish();
		}else if(resultCode == 5){
		String extraData=data.getStringExtra("ComingFrom");
		SharedPreferences.Editor atharyEditor = athary.edit();
		atharyEditor.putString("SAVE", extraData);
		atharyEditor.commit();
		Save_Path = athary.getString("SAVE", "");           
		if (dialogdown != null) dialogdown.dismiss();
		checklibrary();
	}
		else
			initDB();
		}
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {@Override public void onReceive(Context context, Intent serviceIntent) {updateUI(serviceIntent);}};
	private BroadcastReceiver broadcastBufferReceiver = new BroadcastReceiver() {@Override	public void onReceive(Context context, Intent bufferIntent) {showPD(bufferIntent);}};
	private void stopMyPlayService() {isplaying = false; if (mBroadcastIsRegistered) {try {unregisterReceiver(broadcastReceiver); mBroadcastIsRegistered = false;} catch (Exception e) {e.printStackTrace(); Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();}} try {stopService(serviceIntent);} catch (Exception e) {e.printStackTrace();	Toast.makeText(getApplicationContext(),	e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();} boolMusicPlaying = false;}
	private void BufferDialogue() {pdBuff = ProgressDialog.show(IntroActivity.this, "تحميل المادة الصوتية", "الرجاء الانتظار", true);}
	private boolean checkConnectivity() {ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileInfo = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiInfo = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo wimaxInfo = connec.getNetworkInfo(ConnectivityManager.TYPE_WIMAX); if ((mobileInfo != null && mobileInfo.isConnectedOrConnecting()) ||	(wifiInfo != null && wifiInfo.isConnectedOrConnecting()) ||	(wimaxInfo != null && wimaxInfo.isConnectedOrConnecting())) return true; return false;}
	protected Dialog onCreateDialog(int id) {switch(id) {case DIALOG_PROGRESS: moProgressDialog = new ProgressDialog(IntroActivity.this); moProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); moProgressDialog.setTitle("الرجاء الانتظار..."); moProgressDialog.setMessage("تحديث قاعدة البيانات.."); moProgressDialog.setCancelable(false); return moProgressDialog; default: return null;}} 
	private static View createTabView(final Context context, final String text) {View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null); TextView tv = (TextView) view.findViewById(R.id.tabsText); tv.setText(text); return view;}
	@Override protected void onPause() {if (mBufferBroadcastIsRegistered) {unregisterReceiver(broadcastBufferReceiver);	mBufferBroadcastIsRegistered = false;} super.onPause();}
	@Override protected void onResume() {if (!mBufferBroadcastIsRegistered) {registerReceiver(broadcastBufferReceiver, new IntentFilter(PlayService.BROADCAST_BUFFER)); mBufferBroadcastIsRegistered = true;}	super.onResume();} 

	//BackgroundAsyncTask for Update
	public class BackgroundAsyncTask extends AsyncTask<String, Integer, Void> {
		String[] files = null; URL url= null; private int fileLength;
		@Override protected void onPreExecute() {showDialog(DIALOG_PROGRESS);}
		@Override protected Void doInBackground(String... aurl) { 
		  try {   
			  Calendar c = Calendar.getInstance(); 
			  url = new URL((c.get(Calendar.MINUTE) % 2) == 1 ? "http://maknoon.com/alathary/" + aurl[0] : "http://maknoon.com/alathary/" + aurl[0]);
	          URLConnection connection = url.openConnection(); connection.connect(); fileLength = connection.getContentLength();
	          InputStream input = new BufferedInputStream(url.openStream());
	          OutputStream output = new FileOutputStream(getApplicationContext().getFilesDir().toString() + "/update.zip");
	          byte data[] = new byte[1024]; long total = 0; int count;
	          while ((count = input.read(data)) != -1) {total += count; output.write(data, 0, count); publishProgress((int) (total * 100 / fileLength));}
	          output.flush(); output.close(); input.close();      
	      }
	      catch (Exception e){e.printStackTrace();}
		  
		 try  { 
		   FileInputStream fin = new FileInputStream(getApplicationContext().getFilesDir().toString() + "/update.zip"); 
		   ZipInputStream zin = new ZipInputStream(fin); 
		   ZipEntry ze = null;  
		   while ((ze = zin.getNextEntry()) != null) { 
		     if(ze.isDirectory()) {File f = new File(aurl[0] + ze.getName()); if(!f.isDirectory()) f.mkdirs();} 
		     else { 
		       FileOutputStream fout = new FileOutputStream(getApplicationContext().getFilesDir().toString() + "/" + ze.getName());
		       byte[] buffer = new byte[1024]; int length;
		       while ((length = zin.read(buffer))>0) {fout.write(buffer, 0, length);}
		       zin.closeEntry(); fout.close(); 
		     } 
		   } 
			    zin.close();
			    File zippedfile = new File(getApplicationContext().getFilesDir().toString() + "/" + "update.zip"); zippedfile.delete();
			}
			catch (Exception e){e.printStackTrace();}
	
		  	try {mDbHelper.newver(DATABASE_VERSION);
		  	String next[] = {}; File file1 = new File(getApplicationContext().getFilesDir().toString() + "/" + "sh1.csv"); CSV_Reader reader = new CSV_Reader(new InputStreamReader(new FileInputStream(getApplicationContext().getFilesDir().toString() + "/" + "sh1.csv")), '#', '@',0); for(;;) {next = reader.readNext(); if(next != null) {
      mDbHelper.newshaikh( (int) (Integer.valueOf(next[0]) + max_sheekh_id), next[1], 1);
        	} else {break;}} file1.delete(); publishProgress((int) (25));
		    } catch (IOException e) {e.printStackTrace();}
			  
		    try {String next[] = {};
		    File file2 = new File(getApplicationContext().getFilesDir().toString() + "/" + "bk1.csv"); CSV_Reader reader = new CSV_Reader(new InputStreamReader(new FileInputStream(getApplicationContext().getFilesDir().toString() + "/" + "bk1.csv")), '#', '@',0);
	        for(;;) {next = reader.readNext(); if(next != null) {
      mDbHelper.newbook((int) (Integer.valueOf(next[0]) + max_sheekh_id), Integer.valueOf(next[1]), next[2], 1);
            } else {break;}} file2.delete(); publishProgress((int) (50));
		    } catch (IOException e) {e.printStackTrace();}
	
		    try {String next[] = {};
		    File file3 = new File(getApplicationContext().getFilesDir().toString() + "/" + "chap1.csv"); CSV_Reader reader = new CSV_Reader(new InputStreamReader(new FileInputStream(getApplicationContext().getFilesDir().toString() + "/" + "chap1.csv")), '#', '@',0);
	        for(;;) {next = reader.readNext(); if(next != null) {
      mDbHelper.newChapter((int) (Integer.valueOf(next[0]) + max_code), (int) (Integer.valueOf(next[1]) + max_sheekh_id), Integer.valueOf(next[2]), next[3], next[4], next[5], next[6]);
            } else {break;}} file3.delete(); publishProgress((int) (75));} catch (IOException e) {e.printStackTrace();}

		    try {String next[] = {};
		    File file4 = new File(getApplicationContext().getFilesDir().toString() + "/" + "cont1.csv"); CSV_Reader reader = new CSV_Reader(new InputStreamReader(new FileInputStream(getApplicationContext().getFilesDir().toString() + "/" + "cont1.csv")), '#', '@',0);
	        for(;;) {next = reader.readNext();
            if(next != null) {moProgressDialog.setMax(100);
      if (next.length == 8) mDbHelper.newContent((int) (Integer.valueOf(next[0]) + max_code), (int) (Integer.valueOf(next[1]) + max_sheekh_id), Integer.valueOf(next[2]), Integer.valueOf(next[3]), next[4], next[5], next[6], next[7], 0);
      else mDbHelper.newContent((int) (Integer.valueOf(next[0]) + max_code), (int) (Integer.valueOf(next[1]) + max_sheekh_id), Integer.valueOf(next[2]), Integer.valueOf(next[3]), next[4], next[5], next[6], "", 0);
	        } else {break;}} file4.delete(); publishProgress((int) (95));
		    } catch (IOException e) {e.printStackTrace();}

		    try {String next[] = {};
		    File file5 = new File(getApplicationContext().getFilesDir().toString() + "/" + "concat1.csv"); CSV_Reader reader = new CSV_Reader(new InputStreamReader(new FileInputStream(getApplicationContext().getFilesDir().toString() + "/" + "concat1.csv")), '#', '@',0);
	        for(;;) {next = reader.readNext(); if(next != null) {
	  mDbHelper.newContentCat((int) (Integer.valueOf(next[0]) + max_code), Integer.valueOf(next[1]), Integer.valueOf(next[2]), (int) (Integer.valueOf(next[3]) + max_sheekh_id), Integer.valueOf(next[4]));
            } else {break;}} file5.delete(); publishProgress((int) (100));
		    } catch (IOException e) {e.printStackTrace();}
		    
		    return null; 
			}
		@Override protected void onProgressUpdate(Integer... progress) {moProgressDialog.setProgress(progress[0]);}
		@Override protected void onPostExecute(Void unused) {try {dismissDialog(DIALOG_PROGRESS);} catch (Exception e) {}}
		}
}
