package gov.nasa.jpl.issm;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.DoubleBuffer;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class GalleryImage extends BaseActivity {

	private GalleryDescription description;
	private ImageView selectedImageView;
	private TextView selectedTextView;
	private ImageView photoState;
	private ImageView infoState;
	private ImageView leftArrowImageView;

	private ImageView rightArrowImageView;

	private Gallery gallery;
	private Bitmap b;

	private int selectedImagePosition = 0;

	// private List<Drawable> drawables;
	private List<Integer> drawables;

	private GalleryAdapter galImageAdapter;

	private boolean isFirstImage = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery);
		transition();
		// int w = getResources().getDisplayMetrics().widthPixels;
		// long h = w / 16 * 9;
		// LayoutParams params = ((ImageView)
		// findViewById(R.id.container)).getLayoutParams();
		// params.height = (int) h;
		// params.width = (int) w;
		// Log.i("Height: ", String.valueOf(params.height));
		// Log.i("Width: ", String.valueOf(params.width));

		getDrawablesList();
		setupUI();
	}

	private void setupUI() {

		selectedImageView = (ImageView) findViewById(R.id.front_view);
		// selectedTextView = (TextView) findViewById(R.id.back_view);
		selectedTextView = (TextView) findViewById(R.id.description);
		// selectedTextView.setVisibility(View.GONE);
		photoState = (ImageView) findViewById(R.id.photo_stage);
		infoState = (ImageView) findViewById(R.id.info_stage);
		photoState.setVisibility(View.GONE);
		infoState.setVisibility(View.GONE);
		leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
		rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
		gallery = (Gallery) findViewById(R.id.gallery);
		description = new GalleryDescription(this);
		// Go back to the main menu
		Button homeTab = (Button) findViewById(R.id.play_tab);
		homeTab.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(GalleryImage.this, MenuPage.class);
				// i.putExtra("pathToFile", MenuPage.getISSMPath());
				startActivity(i);
				finish();
			}
		});
		// navigate to youtube video
		Button video = (Button) findViewById(R.id.video_tab);
		video.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// String url = "http://www.youtube.com/watch?v=KlDO0C8r_ws";
				// Intent i = new Intent(Intent.ACTION_VIEW);
				// i.setData(Uri.parse(url));
				Intent i = new Intent(GalleryImage.this, VideoActivity.class);
				startActivity(i);
				finish();
			}
		});
		// pop up a text box that contains information about ISSM
		final Button intro = (Button) findViewById(R.id.about_tab);
		intro.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// LayoutInflater layoutInflater =
				// (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
				// View popupView = layoutInflater.inflate(R.layout.popuptext,
				// null);
				// final PopupWindow popupWindow = new PopupWindow( popupView,
				// 400,600, true);
				// popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
				// Button dismiss =
				// (Button)popupView.findViewById(R.id.dismiss);
				// dismiss.setOnClickListener(new Button.OnClickListener()
				// {
				// public void onClick(View v)
				// {
				// popupWindow.dismiss();
				// }
				// });
				Intent i = new Intent(GalleryImage.this, AboutActivity.class);
				startActivity(i);
				finish();
			}
		});
		// Show Team Website
		Button visitus = (Button) findViewById(R.id.team_tab);
		visitus.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// String url = "http://issm.jpl.nasa.gov/";
				// Intent i = new Intent(Intent.ACTION_VIEW);
				// i.setData(Uri.parse(url));
				// startActivity(i);

				Intent i = new Intent(GalleryImage.this, TeamActivity.class);
				startActivity(i);
				finish();
			}
		});

		selectedImageView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(GalleryImage.this,
						ZoomImageViewActivity.class);
				i.putExtra("imagePosition", selectedImagePosition);
				startActivity(i);

			}
		});

		infoState.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (isFirstImage) {
					applyRotation(0, 90);
					isFirstImage = !isFirstImage;

				} else {
					applyRotation(0, -90);
					isFirstImage = !isFirstImage;
				}
			}
		});

		leftArrowImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (selectedImagePosition > 0) {
					--selectedImagePosition;
				}

				gallery.setSelection(selectedImagePosition, false);
			}
		});

		rightArrowImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (selectedImagePosition < drawables.size() - 1) {
					++selectedImagePosition;
				}

				gallery.setSelection(selectedImagePosition, false);

			}
		});

		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {

				selectedImagePosition = pos;

				if (selectedImagePosition > 0
						&& selectedImagePosition < drawables.size() - 1) {

					leftArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.arrow_left_enabled));
					rightArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.arrow_right_enabled));
				} else if (selectedImagePosition == 0) {

					leftArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.arrow_left_disabled));
				} else if (selectedImagePosition == drawables.size() - 1) {

					rightArrowImageView.setImageDrawable(getResources()
							.getDrawable(R.drawable.arrow_right_disabled));
				}

				changeBorderForSelectedImage(selectedImagePosition);
				setSelectedImage(selectedImagePosition);
			}

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

			}

		});

		galImageAdapter = new GalleryAdapter(this, drawables);

		gallery.setAdapter(galImageAdapter);

		if (drawables.size() > 0) {

			gallery.setSelection(selectedImagePosition, false);

		}

		if (drawables.size() == 1) {

			rightArrowImageView.setImageDrawable(getResources().getDrawable(
					R.drawable.arrow_right_disabled));
		}

	}

	private void changeBorderForSelectedImage(int selectedItemPos) {

		int count = gallery.getChildCount();

		for (int i = 0; i < count; i++) {

			ImageView imageView = (ImageView) gallery.getChildAt(i);
			imageView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.image_border));
			imageView.setPadding(3, 3, 3, 3);

		}

		ImageView imageView = (ImageView) gallery.getSelectedView();
		imageView.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.selected_image_border));
		imageView.setPadding(3, 3, 3, 3);
	}

	private void getDrawablesList() {

		drawables = new ArrayList<Integer>();
		int resID;
		for (int i = 0; i < 17; i++) {
			resID = getResources().getIdentifier("image" + i, "drawable",
					getPackageName());
			drawables.add(resID);

		}
	}

	private void setSelectedImage(int selectedImagePosition) {

		int width = (int) (getResources().getDisplayMetrics().widthPixels);
		int height = (int) (getResources().getDisplayMetrics().heightPixels);
		Bitmap b;
		// pre-load implementation
		b = ImageList.getLargeImages().get(selectedImagePosition);
		// b = Bitmap.createScaledBitmap(b, width, height, true);
		selectedImageView.setImageBitmap(b);
		selectedImageView.setScaleType(ScaleType.FIT_XY);
		selectedTextView.setText(description
				.getDescription(selectedImagePosition));
		// resource implementation
		// b = ImageResizer.decodeSampledBitmapFromResource(getResources(),
		// drawables.get(selectedImagePosition), width, height);
		// b = Bitmap.createScaledBitmap(b, width, height, true);
		// selectedImageView.setImageBitmap(b);
		// selectedImageView.setScaleType(ScaleType.FIT_XY);
		// selectedTextView.setText(description
		// .getDescription(selectedImagePosition));
		// asset implementation
		// b = ImageResizer.decodeSampledBitmapFromAsset(is,
		// width, height);
		// selectedImageView.setImageBitmap(Bitmap.createScaledBitmap(b, width,
		// height, true));
		// selectedImageView.setScaleType(ScaleType.FIT_XY);
		// selectedTextView.setText(description
		// .getDescription(selectedImagePosition));
	}

	private void applyRotation(float start, float end) {
		// Find the center of image
		final float centerX = photoState.getWidth() / 2.0f;
		final float centerY = photoState.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final FlipAnimation rotation = new FlipAnimation(start, end, centerX,
				centerY);
		final FlipAnimation rotation2 = new FlipAnimation(start, end, centerX,
				centerY);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(isFirstImage,
				infoState, photoState));
		rotation2.setDuration(500);
		rotation2.setFillAfter(true);
		rotation2.setInterpolator(new AccelerateInterpolator());
		rotation2.setAnimationListener(new DisplayNextView(isFirstImage,
				selectedImageView, selectedTextView));

		if (isFirstImage) {
			infoState.startAnimation(rotation);
			selectedImageView.startAnimation(rotation2);
		} else {
			photoState.startAnimation(rotation);
			selectedTextView.startAnimation(rotation2);
		}

	}

	@Override
	public void onBackPressed() {
		Intent i = new Intent(GalleryImage.this, MenuPage.class);
		startActivity(i);
		finish();
	}
}
