package com.team5.aLife.Client;

import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class WirelessSensorActivity extends Activity{
	
	private final int REFRESH = 1;
	private final int NOTIFICATION = 2;
	
	private ProgressDialog m_ProgressDialog = null; 	// progress dialog
	
	TextView deviceName, status;
	
	Button activate;
	
	private Intent myIntent;
	
	private Device returnedDevice;
	
	private Gson gson = new Gson();
	private final String delimiter = "[&]+";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zigbee_switch_layout);
        
        deviceName = (TextView) findViewById(R.id.SwitchDeviceName);
        status = (TextView) findViewById(R.id.SwitchStatus);
        activate = (Button) findViewById(R.id.SwitchGarageDoor);
        
        activate.setOnClickListener(activateListener);
        
    }
    
    public void onStart()
    {
    	super.onStart();
        
    	m_ProgressDialog = ProgressDialog.show(WirelessSensorActivity.this,    
                "Please wait...", "Retrieving data ...", true);
    	
    	String replyString = socketDispatch.instance().sendReceive(new GetDeviceStateRequest(DeviceListActivity.selectedDevice));
    	
    	String[] tokens = replyString.split(delimiter);
        
    	GetDeviceReply deviceStateReply = gson.fromJson(tokens[1], GetDeviceReply.class);
    	
    	returnedDevice = deviceStateReply.getDevice();
        
        deviceName.setText(returnedDevice.getDeviceName());
        
        if(DeviceListActivity.selectedDevice.getZigbeeStatus() != 1)
        {
        	status.setText("Unavailable");
        	activate.setText("Unavailable");
        	status.setTextColor(Color.GRAY);
        }
        else if(returnedDevice.getDeviceStatus() == 1)
        {
        	status.setText("Opened");
        	activate.setText("Close");
        	status.setTextColor(Color.GREEN);
        }
        else
        {
        	status.setText("Closed");
        	activate.setText("Open");
        	status.setTextColor(Color.RED);
        }
        
        // Turn off the progess dialog
        m_ProgressDialog.dismiss();
    }
    
    // Populate the pop-up menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
 	   menu.add(0, REFRESH, 0, "Refresh");
 	   menu.add(0, NOTIFICATION, 0, "Set up notification");
 	   return true;
    }
    
    // Handle menu selections
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
 	   // Handle menu item selection
 	   switch (item.getItemId()){
 	   
 	   case REFRESH:
 		   onStart();
 		   return true;
 	   case NOTIFICATION:
 		   myIntent = new Intent();
	       myIntent.setClassName("com.team5.aLife.Client",
	                             "com.team5.aLife.Client.NotificationPowerActivity");
	       startActivity(myIntent);
	       return true;
 	   default: return super.onOptionsItemSelected(item);
 	   }
    }
    
    private View.OnClickListener activateListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	m_ProgressDialog = ProgressDialog.show(WirelessSensorActivity.this,    
                    "Please wait...", "Retrieving data ...", true);
        	
        	boolean wasTransactionSuccessful;
        	
        	if (returnedDevice.getDeviceStatus() == 0)
        	{
        		
        		String replyString = socketDispatch.instance().sendReceive(
        							 new UpdateDeviceStateRequest(DeviceListActivity.selectedDevice, UpdateDeviceStateRequest.Action.ACTIVATE));
            	
            	String[] tokens = replyString.split(delimiter);
            	
            	TransactionReply updateDeviceStateReply = (TransactionReply) gson.fromJson(tokens[1], TransactionReply.class);
            	
        		wasTransactionSuccessful = updateDeviceStateReply.wasTransactionSuccessful();
        	}
        	else
        	{
        		String replyString = socketDispatch.instance().sendReceive(
        							 new UpdateDeviceStateRequest(DeviceListActivity.selectedDevice, UpdateDeviceStateRequest.Action.DEACTIVATE));
            	
            	String[] tokens = replyString.split(delimiter);
            	
            	TransactionReply updateDeviceStateReply = (TransactionReply) gson.fromJson(tokens[1], TransactionReply.class);
            	
        		wasTransactionSuccessful = updateDeviceStateReply.wasTransactionSuccessful();
        	}
        	
        	m_ProgressDialog.dismiss();
        	
        	if (!wasTransactionSuccessful)
        	{
        		AlertDialog.Builder builder = new AlertDialog.Builder(WirelessSensorActivity.this);
            	builder.setMessage("The transaction failed, please try again")
            	       .setCancelable(false)
            	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   //RegisterDeviceActivity.this.finish();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	alert.show();
        	}
        	else
        	{
        		AlertDialog.Builder builder = new AlertDialog.Builder(WirelessSensorActivity.this);
            	builder.setMessage("Transaction Complete")
            	       .setCancelable(false)
            	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   //RegisterDeviceActivity.this.finish();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	alert.show();
        	}
        	
        	onStart();
            
        }
    };

}
