package gr.mybook.myintentservice;

import gr.mybook.myintentservice.myService;
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.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Activity_1 extends Activity {
	Button btn;
	private ResponseReceiver receiver;
	TextView textView;
	public static final String msg1="SERVICE CALL";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_1);
        
        btn = (Button) findViewById(R.id.button1);
        textView = (TextView) findViewById(R.id.textView1);
        
        // Intent filter for the broadcast receiver with the desired action
        IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new ResponseReceiver();
        registerReceiver(receiver, filter);

    }
    
    @Override
    public void onDestroy() {
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }

    public void  onClick(View view) {
        /*
         * Creates a new Intent to start myService
         * Passes a message to service  
         */
        Intent myIntent = new Intent(this, myService.class);
        // Pass a message in Intent’s data field
        myIntent.putExtra(myService.PARAM_IN_MSG, msg1);
        startService(myIntent);
    }

    public class ResponseReceiver extends BroadcastReceiver {
 	   public static final String ACTION_RESP = "gr.ellinas.intent.action.MESSAGE_PROCESSED";
 	   
 	   @Override
 	    public void onReceive(Context context, Intent intent) {
 	       String text = intent.getStringExtra(myService.PARAM_OUT_MSG);
	       if (text.equals(myService.msg2)) {
	    	   textView.setText(text);
	    	   btn.setEnabled(false);
	       }
 	   	}
 	}
}