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.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

public class WirelessThermostatActivity extends Activity{
	
	private final int REFRESH = 1;
	
	private ProgressDialog m_ProgressDialog = null; 	// progress dialog
	
	TextView deviceName, currTemp, currSetTemp, currMode;
	
	Spinner modeSpinner;
	
	EditText display;
	
	ImageButton tempUp, tempDown;
	
	Button submit;
	
	private int variableTemp;
	
	private Thermostat thermostat;
	
	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_thermostat_layout);
        
        deviceName = (TextView) findViewById(R.id.ThermoDeviceName);
        currTemp = (TextView) findViewById(R.id.ThermoCurrTemp);
        currSetTemp = (TextView) findViewById(R.id.ThermoSetTemp);
        currMode = (TextView) findViewById(R.id.ThermoMode);
        modeSpinner = (Spinner) findViewById(R.id.ThermoModeSpin);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.thermo_mode_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        modeSpinner.setAdapter(adapter);
        
        display = (EditText) findViewById(R.id.ThermoDisplay);
        
        
        tempUp = (ImageButton) findViewById(R.id.ThermoTempUp);
        tempDown = (ImageButton) findViewById(R.id.ThermoTempDown);
        submit = (Button) findViewById(R.id.ThermoSubmit);
        
        
    }
    
    public void onStart()
    {
    	super.onStart();
        
    	m_ProgressDialog = ProgressDialog.show(WirelessThermostatActivity.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);
    	
    	Device returnedDevice = deviceStateReply.getDevice();
    	
    	m_ProgressDialog.dismiss();
    	
    	if (returnedDevice != null && returnedDevice.getDeviceType() == Device.DEVICE_TYPE_THERMOSTAT)
    	{
    		
    		tempUp.setOnClickListener(tempUpListener);
    		tempDown.setOnClickListener(tempDownListener);
    		submit.setOnClickListener(submitListener);
    		
    		thermostat = (Thermostat) returnedDevice;

    		variableTemp = thermostat.getCurrentSetTemp();
    		deviceName.setText(thermostat.getDeviceName());
    		currTemp.setText(""+thermostat.getCurrentTemp()); 
    		currSetTemp.setText(""+thermostat.getCurrentSetTemp());
    		currMode.setText(thermostat.getCurrentMode());
    		
    		display.setText(variableTemp + " deg");
    		
    		
    		if (thermostat.getCurrentTemp() > thermostat.getCurrentSetTemp())
    			currTemp.setTextColor(Color.RED);
    		else if(thermostat.getCurrentTemp() < thermostat.getCurrentSetTemp())
    			currTemp.setTextColor(Color.BLUE);
    		
    	}
    	else
    	{
    		AlertDialog.Builder builder = new AlertDialog.Builder(WirelessThermostatActivity.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) {
        	        	   //WirelessThermostatActivity.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");
 	   return true;
    }
    
    // Handle menu selections
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
 	   // Handle menu item selection
 	   switch (item.getItemId()){
 	   
 	   case REFRESH:
 		   onStart();
 		   return true;
 	   default: return super.onOptionsItemSelected(item);
 	   }
    }
    
    private View.OnClickListener tempUpListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	variableTemp++;
        	display.setText(variableTemp + " deg");
        }
    
    };
    
    private View.OnClickListener tempDownListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	variableTemp--;
        	display.setText(variableTemp + " deg");
        	
        }
    
    };
    
    private View.OnClickListener submitListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	m_ProgressDialog = ProgressDialog.show(WirelessThermostatActivity.this,    
                    "Please wait...", "Retrieving data ...", true);
        	
        	int newStatus;
        	
        	if (modeSpinner.getSelectedItem().toString().equals("Off"))
        		newStatus = 0;
        	else
        		newStatus = 1;
        	
        	Thermostat updatedThermostat = new Thermostat(thermostat.getDeviceID(),
														  thermostat.getDeviceType(), 
														  thermostat.getDeviceName(), 
														  thermostat.getDeviceAddress(),
														  thermostat.getZigbeeStatus(), 
														  newStatus,
														  thermostat.getCurrentTemp(),
														  variableTemp,
														  modeSpinner.getSelectedItem().toString());
        	
        	boolean wasTransactionSuccessful;
        	
        	String replyString = socketDispatch.instance().sendReceive(
					 new UpdateDeviceStateRequest(updatedThermostat, UpdateDeviceStateRequest.Action.UPDATE_PARAMS));

			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(WirelessThermostatActivity.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(WirelessThermostatActivity.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();
            
        }
    };

}
