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.util.Log;
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;
	
	private Intent myIntent;
	
	private Gson gson = new Gson();
	private final String delimiter = "[&]+";
	
	private final String TAG = "WirelessPowerSwitchActivity:  ";
	
	/** 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);    
        
    }
    
    public void onStart()
    {
    	super.onStart();
    	
    	m_ProgressDialog = ProgressDialog.show(WirelessPowerSwitchActivity.this,    
                "Please wait...", "Retrieving data ...", true);
    	
    	Log.i(TAG+"onStart", "Deivce Type and Name:  " + DeviceListActivity.selectedDevice.getDeviceType() +
    		  " " + DeviceListActivity.selectedDevice.getDeviceName());
    	
    	String replyString = socketDispatch.instance().sendReceive(new GetDeviceStateRequest(DeviceListActivity.selectedDevice));
    	
    	String[] tokens = replyString.split(delimiter);
        
    	GetDeviceReply deviceStateReply = gson.fromJson(tokens[1], GetDeviceReply.class);
    	
    	Device returnedDevice = deviceStateReply.getDevice();
	
    	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.Client",
	                             "com.team5.aLife.Client.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)
        	{
        		
        		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(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();
            
        }
    };

}
