package com.ociweb.demo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.os.Bundle;
import android.util.Log;
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) {
      Throwable th = (Throwable) intent
          .getSerializableExtra(Constants.EXCEPTION);
      if (th != null) {
        Log.w(HomeActivity.class.getName(), th.toString());
      }
      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);
  }
  
  void setStartEnabled(boolean b) {
    mStartButton.setEnabled(b);
  }
  
  boolean isStartEnabled() {
    return mStartButton.isEnabled();
  }

  public void onClick(View v) {
    if (v == mStartButton) {

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

      Intent intent = new Intent(this, DataFetcher.class);
      startService(intent);
    }
  }

  @Override
  protected void onPause() {
    getApplicationContext().unregisterReceiver(broadcastReceiver);
    super.onPause();
  }

  @Override
  protected void onResume() {
    super.onResume();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
    intentFilter.addAction(Constants.DATA_FETCH_ACTION);
    try {
      intentFilter.addDataType(Constants.DATA_FETCH_TYPE);
    } catch (MalformedMimeTypeException e) {
      throw new RuntimeException(e);
    }

    getApplicationContext().registerReceiver(broadcastReceiver, intentFilter);

  }

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