package net.cs76.lectures.Threads03;

import net.cs76.lectures.Threads03.URLImageAdapter;
import net.cs76.lectures.Threads03.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

/*
 * Threads03
 * Dan Armendariz
 * Computer Science E-76
 * 
 * A sample photo gallery application, based on loosely on
 * Intents08, that now pulls images from the Internet and
 * supports lazy loading via a background thread.
 */
public class Code3 extends Activity implements OnItemClickListener, OnClickListener {

	private URLImageAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// get data generated before a config change, if it exists
		final Object data = getLastNonConfigurationInstance();
		
		// instantiate our adapter, sending in any data
		adapter = new URLImageAdapter(this, data);

		// attach to the grid layout in the UI
		GridView grid = (GridView) findViewById(R.id.gridview);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(this);

		// enable the little textview at the bottom to open a link
		TextView copy = (TextView) findViewById(R.id.copynotice);
		copy.setOnClickListener(this);
	}


	/**
	 * Open new activity to show the selected image
	 * full-screen in a new Activity.
	 */
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

		openPage((String) adapter.getItem(position));
	}


	/**
	 * Open a webpage when the textview is clicked.
	 */
	@Override
	public void onClick(View v) {
		openPage("http://danallan.net");		
	}


	/**
	 * Start a browser activity to display the url passed.
	 */
	public void openPage(String url) {
		// create an intent
		Intent data = new Intent();
		
		// specify the intent's action and url
		data.setAction(Intent.ACTION_VIEW);
		data.setData(Uri.parse(url));
		
    	try {
    		startActivity(data); 
    	} catch (ActivityNotFoundException e) {
    		Log.e("Threads03", "Cannot find an activity to start URL " + url);
    	}

	}

	
	/**
	 * Preserve adapter data between orientation changes
	 * See: http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		return adapter.getData();
	}
}