package com.ociweb.demo;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
      onThreadCompleted();
    }    
  };
  
  private final IntentFilter intentFilter = IntentFilter.create("foo", "bar");

  // 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);
  }

  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();

      // TODO change #1
      Intent intent = new Intent(this, DataFetcher.class);
      startService(intent);
    }
  }
 
  @Override
  protected void onPause() {
    unregisterReceiver(broadcastReceiver);
    super.onPause();
  }

  @Override
  protected void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver, intentFilter);
  }

  /**
   * 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();
  }

}