package athary.audio.ency;

import info.guardianproject.database.sqlcipher.SQLiteDatabase;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import athary.audio.ency.Helpers.data.NotificationHelper;
import athary.audio.ency.Helpers.main.FileChooser;

public class Wizard2 extends Activity{
	
	//Define Views
	private EditText txt_path;
	private ProgressBar progressBar;
	private Button btn_path;
	private Button btn_dw;
	private TextView titleview;
	
	//Define Other Variables
	public String url;
	private String PTH;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wizard2);

        SQLiteDatabase.loadLibs(this);
        
      	initViews();
		Appearance();
		setListeners();
	
	}
	
	 private void initViews() {

			txt_path = (EditText) findViewById(R.id.txt_path);
			btn_path =(Button) findViewById(R.id.btn_path);		
			btn_dw =(Button) findViewById(R.id.btn_dw);		
			titleview = (TextView) findViewById(R.id.titleview);
			progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
	}

	private void Appearance() {

		titleview.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		titleview.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		txt_path.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		txt_path.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		btn_path.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		btn_path.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
		btn_dw.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		btn_dw.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);

		txt_path.setText(getApplicationContext().getFilesDir().toString());
		PTH = txt_path.getText().toString();
	}

	private void setListeners() {

		  btn_path.setOnClickListener(new View.OnClickListener() {
				
			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), FileChooser.class);
				i.putExtra("FLAG", "DOWNLOAD");
				startActivityForResult(i, 0);
			}
		});

		btn_dw.setOnClickListener(new View.OnClickListener() {
			

			@Override
			public void onClick(View v) {
						
		        new BackgroundAsyncTask().execute(PTH);

			}
		});		
	}

	public class BackgroundAsyncTask extends AsyncTask<String, Integer, Void> {

		 AssetManager assetManager = getAssets();
		 String[] files = null;
		 URL url= null;
		 
	  @Override
	  protected void onPreExecute() { 
		  
		  initNotification();
		  
		  progressBar.setProgress(0);
		  progressBar.setSecondaryProgress(0);
		  progressBar.setMax(100);
		  progressBar.setVisibility(View.VISIBLE);
		  txt_path.setEnabled(false);
		  btn_path.setEnabled(false);
		  btn_dw.setEnabled(false);
		  
		    try {
		        files = assetManager.list("");
		    } catch (IOException e) {
		        Log.e("tag", e.getMessage());
		    }
		    
	  }

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

		  try {   
				Calendar c = Calendar.getInstance(); 

				 url = new URL((c.get(Calendar.MINUTE) % 2) == 1 ? "http://maknoon.com/alathary/maindb.zip" : "http://www.alalbany.net/click/go.php?id=1508");
				
	            URLConnection connection = url.openConnection();
	            connection.connect();
	            // this will be useful so that you can show a typical 0-100%
	            // progress bar
	            int fileLength = connection.getContentLength();

	            // download the file
	            InputStream input = new BufferedInputStream(url.openStream());
	            OutputStream output = new FileOutputStream(aurl[0] + "maindb.obb");

	            byte data[] = new byte[1024];
	            long total = 0;
	            int count;
	            while ((count = input.read(data)) != -1) {
	                total += count ;
	                // publishing the progress....
	                output.write(data, 0, count);
	                publishProgress((int) (total * 100 / fileLength));
	            }
	            output.flush();
	            output.close();
	            input.close();      
	        }
	        catch (Exception e){
	            e.printStackTrace();
	        }

		    	   SharedPreferences athary = getSharedPreferences("athary", 0);
		  		   SharedPreferences.Editor editor = athary.edit();
		  		   editor.putString("path", aurl[0] + "maindb.obb");

		  		   //Commit the edits!
		  		   editor.commit();
			       setResult(2);
			   
		  return null; 
		  }

	  @Override
	  protected void onProgressUpdate(Integer... progress) { 
		  
		  progressBar.setProgress(progress[0]);
		  titleview.setText("جاري التحميل..." + "\n" + String.valueOf(progress[0]) + "%");
		  
	  }
	  
	  @Override
	  protected void onPostExecute(Void unused) { 
		  	
		  progressBar.setVisibility(View.INVISIBLE);

		  txt_path.setEnabled(true);
		  btn_path.setEnabled(true);
		  btn_dw.setEnabled(true);
		  
		  cancelNotification();
		  
	  	  finish();
		  
	  }


	 }
	
	private void initNotification() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		int icon = R.drawable.icon;
		CharSequence tickerText = "الموسوعة الصوتية";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;   
		Context context = getApplicationContext();
		CharSequence contentTitle = "الموسوعة الصوتية";
		CharSequence contentText = "تحميل قاعدة البيانات...";//TITLE.replaceAll("\n", " - ");
		Intent notificationIntent = new Intent(this, Wizard2.class);
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,	notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context, contentTitle, contentText,	contentIntent);
		mNotificationManager.notify(1, notification);
		
		//startForeground(1, notification);

	}

	// Cancel Notification
	private void cancelNotification() {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.cancel(1);
		//stopForeground(true);

	}

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

	     String extraData=data.getStringExtra("ComingFrom");
	     txt_path.setText(extraData);
	     PTH = extraData;
	}
	
	
 
	 
}
