package com.team5.aLife.BaseStation;

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.ImageView;
import android.widget.TextView;

public class WirelessPowerSwitchActivity extends Activity{
	
	private final int REFRESH = 1;
	private final int NOTIFICATION = 2;
	
	private ProgressDialog m_ProgressDialog = null; 	// progress dialog
	
	TextView deviceName, status, avgConsumption, totalConsumption, switchLabel;
	
	ImageView switchButton;
	
	PowerSwitchDevice device;
	
	Device returnedDevice;
	
	private Intent myIntent;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zigbee_power_switch_layout);
        
        deviceName = (TextView) findViewById(R.id.PowerDeviceName);
        status = (TextView) findViewById(R.id.PowerStatus);
        avgConsumption = (TextView) findViewById(R.id.PowerAvgConsumed);
        totalConsumption = (TextView) findViewById(R.id.PowerTotalConsumed);
        switchLabel = (TextView) findViewById(R.id.PowerSwitchMessage);
        
        switchButton = (ImageView)findViewById(R.id.PowerSwitchButton);    
        
        returnedDevice = SerialCommunicatonHandler.getDeviceState(DeviceListActivity.selectedDevice);
        
    }
    
    public void onStart()
    {
    	super.onStart();
    	
    	m_ProgressDialog = ProgressDialog.show(WirelessPowerSwitchActivity.this,    
                "Please wait...", "Retrieving data ...", true);
	
    	if (returnedDevice != null && returnedDevice.getDeviceType() == Device.DEVICE_TYPE_POWER_MONITOR_SWITCH)
    	{
    		switchButton.setOnClickListener(switchButtonListener);
    		
    		device = (PowerSwitchDevice) returnedDevice;
    		
    		deviceName.setText(device.getDeviceName());
    		
    		if(device.getDeviceStatus() == 1)
    		{
    			status.setText("On");
    			status.setTextColor(Color.GREEN);
    			
    			switchLabel.setText("Turn Off");
    			switchButton.setImageResource(R.drawable.on_button_green_selector);
    		}
    		else
    		{
    			status.setText("Off");
    			status.setTextColor(Color.RED);
    			
    			switchLabel.setText("Turn Off");
    			switchButton.setImageResource(R.drawable.on_button_red_selector);
    			
    		}
    		
    		avgConsumption.setText(""+device.getAverageConsumption());
    		
            totalConsumption.setText(""+device.getTotalConsumption());
            
            m_ProgressDialog.dismiss();
       
    		
    	}
    	else
    	{
    		AlertDialog.Builder builder = new AlertDialog.Builder(WirelessPowerSwitchActivity.this);
        	builder.setMessage("Please check device settings, your thermostat may not be configured correctly")
        	       .setCancelable(false)
        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   //WirelessPowerSwitchActivity.this.finish();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
    	}
    }
    
    // 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.BaseStation",
	                             "com.team5.aLife.BaseStation.NotificationPowerActivity");
	       startActivity(myIntent);
	       return true;
 	   default: return super.onOptionsItemSelected(item);
 	   }
    }
    
    private View.OnClickListener switchButtonListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	m_ProgressDialog = ProgressDialog.show(WirelessPowerSwitchActivity.this,    
                    "Please wait...", "Retrieving data ...", true);
           
        	boolean wasTransactionSuccessful;
        	
        	if (device.getDeviceStatus() == 0)
        	{
        		wasTransactionSuccessful = SerialCommunicatonHandler.activateDevice(device);
        	}
        	else
        	{
        		wasTransactionSuccessful = SerialCommunicatonHandler.deactivateDevice(device);
        	}
        	
        	m_ProgressDialog.dismiss();
        	
        	if (!wasTransactionSuccessful)
        	{
        		AlertDialog.Builder builder = new AlertDialog.Builder(WirelessPowerSwitchActivity.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(WirelessPowerSwitchActivity.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();
            
        }
    };

}
