package com.ociweb.demo;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity implements OnClickListener {

  private Button mStartButton;
  private TextView mStatusLabel;
  
  private static final String ENABLED_KEY = "com.ociweb.buttonEnabled";


  // background threads use this Handler to post messages to
  // the main application thread
  private final Handler mHandler = new Handler();

  // post this to the Handler when the background thread completes
  private final Runnable mCompleteRunnable = new Runnable() {
    public void run() {
      onThreadCompleted();
    }
  };

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

    mStartButton = (Button) findViewById(R.id.start_background_thread_btn);
    mStatusLabel = (TextView) findViewById(R.id.thread_status_label);

    mStartButton.setOnClickListener(this);
    
    if (savedInstanceState != null) {
      if (savedInstanceState.containsKey(ENABLED_KEY)) {
        mStartButton.setEnabled(savedInstanceState.getBoolean(ENABLED_KEY));
      }
    }
  }
  
  
  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(ENABLED_KEY, mStartButton.isEnabled());
  }

  public void onClick(View v) {
    // System.err.println("onClick(), this = " + System.identityHashCode(this));

    if (v == mStartButton) {

      mStartButton.setEnabled(false);
      mStatusLabel.setText(R.string.thread_running);
      Toast.makeText(this, R.string.thread_running, Toast.LENGTH_SHORT).show();

      Thread t = new Thread() {
        public void run() {
          // perform expensive tasks in a background thread
          expensiveOperation();

          // let the UI know the task is complete
          mHandler.post(mCompleteRunnable);
        }
      };
      t.start();
    }
  }

  /**
   * Call this method on the main application thread once the background thread
   * completes.
   */
  private void onThreadCompleted() {
    // System.err.println("onThreadCompleted(), this = " +
    // System.identityHashCode(this));
    mStartButton.setEnabled(true);
    mStatusLabel.setText(R.string.thread_finished);
    Toast.makeText(this, R.string.thread_finished, Toast.LENGTH_SHORT).show();
  }

  /**
   * This method runs in a background thread. In a real app, it would do
   * something useful, such as getting data from a web service.
   */
  private void expensiveOperation() {
    try {
      TimeUnit.SECONDS.sleep(4);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}