package course.examples.ThreadingSimplePost;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import course.examples.ThreadingThreadingViewPostActivity.R;

public class SimpleThreadingViewPostActivity extends Activity {
	private Bitmap mBitmap;
	private ImageView mImageView;
	private int mDelay = 5000;

	private static final String TAG = "SimpleThreadingViewPostActivity";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mImageView = (ImageView) findViewById(R.id.imageView);

		//Botón Clear
		final Button btnClear = (Button) findViewById(R.id.btnClear);
		//Definimos el manejador del OnClick del boton clear
		btnClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Quitamos la imagen
				mImageView.setImageBitmap(null);
			}
		});


		final Button button = (Button) findViewById(R.id.loadButton);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadIcon();
			}
		});

		final Button otherButton = (Button) findViewById(R.id.otherButton);
		otherButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(SimpleThreadingViewPostActivity.this, "I'm Working",
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	private void loadIcon() {
		//Creation of Thread
		Thread threadLoadIcon;

		//Creation of the Runnable to be passed to the Thread.
		Runnable runThreadRunnable = new Runnable() {

			//Creation of the Runnable to efectively loading the bitmap in the UI-Thread
			Runnable runBitmapLoader = new Runnable() {
						@Override
						public void run() {
							Log.d(TAG,"Running Runnable runBitmapLoader");
							mImageView.setImageBitmap(mBitmap);
						}
					};

			@Override
			public void run() {
				Log.d(TAG,"Running Runnable runThreadRunnable State: "+ Thread.currentThread().getState());
				try {
					Thread.sleep(mDelay);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.painter);
				mImageView.post(runBitmapLoader);
			}

		};
		threadLoadIcon =  new Thread(runThreadRunnable);
		threadLoadIcon.start();
	}
}