package gov.nasa.jpl.issm;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;

/////////////////////////////////////////////////////////////////////////// 
public class ISSMAPP extends Activity {
	ImageList imageList;
	private static final String PREFERENCE_FIRST_RUN = null;
	public static String extStorageDirectory;
	private String issmFolder;
	SharedPreferences settings;
	private ProgressDialog progressDialog;

	// ------------------------------------------------------------------------
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splashscreen);
		settings = this.getSharedPreferences("MenuPage", 0);
		final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
				|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {

			// temporary: display modes without messing with the network to
			// be able to access offline mode
			// AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// builder.setMessage("Pick a mode");
			// CharSequence[] options = { "Native", "Offline", "Online" };
			// builder.setItems(options, new DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog, int which) {
			// switch (which) {
			// case 0:
			// boolean firstrun = settings.getBoolean(
			// PREFERENCE_FIRST_RUN, true);
			// extStorageDirectory = Environment
			// .getExternalStorageDirectory().toString();
			// issmFolder = extStorageDirectory + "/ISSM/input_files/";
			// imageList = new ImageList(ISSMAPP.this);
			// new CopyDataTask().execute(firstrun);
			// break;
			// case 1:
			// Intent j = new Intent(ISSMAPP.this,
			// ISSMWebActivity.class);
			// j.putExtra("mode", 1);
			// startActivity(j);
			// finish();
			// break;
			// case 2:
			// Intent i = new Intent(ISSMAPP.this,
			// ISSMWebActivity.class);
			// i.putExtra("mode", 0);
			// startActivity(i);
			// finish();
			// break;
			// }
			// }
			// });
			// builder.create().show();
			new AlertDialog.Builder(this)
					.setMessage("Pick a mode")
					.setCancelable(false)
					.setPositiveButton("Online",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent i = new Intent(ISSMAPP.this,
											ISSMWebActivity.class);
									i.putExtra("mode", 0);
									startActivity(i);
									finish();
								}
							})
					.setNeutralButton("Offline",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent i = new Intent(ISSMAPP.this,
											ISSMWebActivity.class);
									i.putExtra("mode", 1);
									startActivity(i);
									finish();
								}
							})
					.setNegativeButton("Native",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									boolean firstrun = settings.getBoolean(
											PREFERENCE_FIRST_RUN, true);
									extStorageDirectory = Environment
											.getExternalStorageDirectory()
											.toString();
									issmFolder = extStorageDirectory
											+ "/ISSM/input_files/";
									imageList = new ImageList(ISSMAPP.this);
									new CopyDataTask().execute(firstrun);
								}
							}).show();

		} else {
			boolean firstrun = settings.getBoolean(PREFERENCE_FIRST_RUN, true);
			extStorageDirectory = Environment.getExternalStorageDirectory()
					.toString();
			issmFolder = extStorageDirectory + "/ISSM/input_files/";
			imageList = new ImageList(this);
			new CopyDataTask().execute(firstrun);
		}
	}

	// -------------------------------------------------------------------------------------------
	// Start the splashscreen at beginning while transferring
	// data file from Assets folder to SDcard
	private class CopyDataTask extends AsyncTask<Boolean, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Boolean... target) {
			// imageList.decodeAndResizeImageFromURL();
			imageList.decodeAndResizeImage();
			imageList.decodeLargeImage();
			// not sure why, but target[0] can be true on install! more to be
			// done.
			// if(target[0] = false)
			// {
			SharedPreferences.Editor e = settings.edit();
			e.putBoolean(PREFERENCE_FIRST_RUN, false);

			e.commit();
			// If not, run these methods:
			SetDirectory(issmFolder);
			// }
			return true;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(ISSMAPP.this);
			progressDialog.setMessage("Loading Data");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		protected void onPostExecute(Boolean result) {
			progressDialog.dismiss();
			Log.i("imageList size: ",
					String.valueOf(ImageList.getImageList().size()));
			Log.i("largeImageList size: ",
					String.valueOf(ImageList.getLargeImages().size()));
			Intent i = new Intent(ISSMAPP.this, MenuPage.class);
			i.putExtra("pathToFile", issmFolder);
			startActivity(i);
		}
	}

	// -------------------------------------------------------------------------------------------
	private void SetDirectory(String directory) {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File txtDirectory = new File(issmFolder);

			// Check and create directory in SDcard
			if (!txtDirectory.exists()) {
				txtDirectory.mkdirs();
			}
			CopyAssets(); // Then run the method to copy the file.

		} else if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED_READ_ONLY)) {
			Toast toast = Toast.makeText(this.getApplicationContext(),
					"Memory is not mounted to device", Toast.LENGTH_LONG);
			toast.show();
		}

	}

	// ----------------------------------------------------------------------------
	/**
	 * -- Copy the file from the assets folder to the sdCard
	 * ===========================================================
	 **/
	private void CopyAssets() {
		AssetManager assetManager = getAssets();
		String[] files = null;
		try {
			files = assetManager.list("Map");
		} catch (IOException e) {
			Log.e("tag", e.getMessage());
		}
		for (int i = 0; i < files.length; i++) {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = assetManager.open("Map/" + files[i]);
				out = new FileOutputStream(issmFolder + files[i]);
				copyFile(in, out);
				in.close();
				in = null;
				out.flush();
				out.close();
				out = null;
			} catch (Exception e) {
				Log.e("tag", e.getMessage());
			}
		}
	}

	// ----------------------------------------------------------------------------
	private void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

	// ----------------------------------------------------------------------------
	public void transition() {
		overridePendingTransition(R.anim.left_out_fast, R.anim.left_out);
	}

	// ----------------------------------------------------------------------------
	private void StartAnimations() {
		Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
		anim.reset();
		LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
		l.clearAnimation();
		l.startAnimation(anim);

		anim = AnimationUtils.loadAnimation(this, R.anim.translate);
		anim.reset();
		ImageView iv = (ImageView) findViewById(R.id.logo);
		iv.clearAnimation();
		iv.startAnimation(anim);
	}
	// -------------------------------------------------------------------------------
}
// ////////////////////////////////////////////////////////////////////////////////
