package com.team5.aLife.Client;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class DeviceListActivity extends ListActivity {
	
	// TODO: See http://stackoverflow.com/questions/3044049/android-listview-onclick-event-in-the-tabs for the FLIPPER???
	
    private static final String TAG = "DeviceListActivity:  ";
    
    protected static Device selectedDevice = null;
    private ProgressDialog m_ProgressDialog = null; 	// progress dialog
    private ArrayList<Device> deviceList = null;		// holds our device list
    private DeviceAdapter dAdapter;						// custom class that extends ArrayAdapter

    private Intent myIntent;
    
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.devicelist);
        
        registerForContextMenu(getListView());
        
        deviceList = new ArrayList<Device>();			// create a new array of devices
        // Create the row adapter for the ListView        
        this.dAdapter = new DeviceAdapter(this, R.layout.listviewrow, deviceList);
        // Set the ROW adapter for the ListView
        setListAdapter(this.dAdapter);
        // Bind the Device selection

        // Get the device list from the server in JSON format
        refreshDevices();
                
    } // end onCreate

	protected void onListItemClick(ListView l, View v, int position, long id){
		
		selectedDevice = deviceList.get(position);
		
		switch (selectedDevice.getDeviceType()){	   
	 	   case Device.DEVICE_TYPE_THERMOSTAT:
	 		   Log.i(TAG + "onListItemClick", "Selected a thermostat");
	 		   myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.WirelessThermostatActivity");
		       startActivity(myIntent);
	 		   break;
	 	  case Device.DEVICE_TYPE_POWER_MONITOR_SWITCH:
	 		   Log.i(TAG + "onListItemClick", "Selected a power monitor with switch");
	 		   myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.WirelessPowerSwitchActivity");
		       startActivity(myIntent);
	 		   break;
	 	  case Device.DEVICE_TYPE_SWITCH:
	 		   Log.i(TAG + "onListItemClick", "Selected a switch device");
	 		   myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.WirelessSwitchActivity");
		       startActivity(myIntent);
	 		   break;
	 	  case Device.DEVICE_TYPE_WIRELESS_SENSOR:
	 		   Log.i(TAG + "onListItemClick", "Selected a wireless sensor");
	 		   myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.WirelessSensorActivity");
		       startActivity(myIntent);
	 		   break;
	 	  default: 
	 		   super.onListItemClick(l, v, position, id);
	 	  	   break;
		}
    	
    }

    public void onResume()
    {
    	super.onResume();
    	refreshDevices();
    }
    
    private void refreshDevices(){
    	// Since this is a network action show the progress dialog
        m_ProgressDialog = ProgressDialog.show(this,    
                "Please wait...", "Retrieving data ...", true);
        
        // reset the device list to empty
        deviceList.clear();
        
        // Create the request object and send the request
        GetAllDevicesRequest gr = new GetAllDevicesRequest();
        String s = socketDispatch.instance().sendReceive(gr);
        Log.i(TAG +"refreshDevices", "Received: " + s); 
        
        // Turn off the progress dialog
        //m_ProgressDialog.dismiss();
        
        // Strip off the 102& header
        s = s.substring(4, s.length());
        
        // reset the device list to empty
        deviceList.clear();
        
        // If there was a response then turn it into
        // an ArrayList<Device> for the ListView
        if (s != null){
        	deviceList = parseResponse.instance().toArrayListDevice(s);
            Log.i(TAG + "refreshDevices", "deviceList has " + deviceList.size() + " devices");
            // Let the ListView know there is new data to display
            runOnUiThread(updateListView);
        }
        
    }
    
    private Runnable updateListView = new Runnable() {

        @Override
        public void run() {
        	Log.i(TAG+"updateListView.run()", "updateListView is being run");
            if(deviceList != null && deviceList.size() > 0)
            {
                dAdapter.notifyDataSetChanged();
                // Clear all items so they don't start stacking up
                dAdapter.clear();
                Log.i(TAG+"updateListView.run()", "deviceList is not null and has size > 0.  Devicelist size is " + deviceList.size());
                for(int i=0; i<deviceList.size(); i++)
                {
                	dAdapter.add(deviceList.get(i));
                	Log.i(TAG+"updateListView.run()", "Iterating through device list " + i);
                }
            }
            m_ProgressDialog.dismiss();
            dAdapter.notifyDataSetChanged();
            Log.i(TAG+"updateListView.run()", "Should be done updating adapter");
        }
    };
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      menu.setHeaderTitle("Options");
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.layout.context_menu_devicelist, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      switch (item.getItemId()) {
      case R.id.Contextmenu_Edit:
    	selectedDevice = deviceList.get((int)info.id);
    	myIntent = new Intent();
		myIntent.setClassName("com.team5.aLife.Client",
                              "com.team5.aLife.Client.EditDeviceActivity");
        startActivity(myIntent);
        Log.i(TAG+"onContextItemSelected", "I clicked on id " + info.id);
        return true;
      default:
        return super.onContextItemSelected(item);
      }
    }
    
    // Handle menu selections
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
 	   // Handle menu item selection
 	   switch (item.getItemId()){
 	   
 	   case R.id.Menu_RefreshList:
 		   Log.i("customListView:Options", "Menu:Refresh List");
 		   refreshDevices();
 		   return true;
 		   
 	   case R.id.Menu_AddDevice:
 		   myIntent = new Intent();
  		   myIntent.setClassName("com.team5.aLife.Client",
                                 "com.team5.aLife.Client.AddDeviceActivity");
           startActivity(myIntent);
 		   Log.i("customListView:Options", "Menu:Add Device");
 		   return true;
 		
 	   case R.id.Menu_Notifications:
 		   myIntent = new Intent();
 		   myIntent.setClassName("com.team5.aLife.Client",
                                 "com.team5.aLife.Client.NotificationActivity");
           startActivity(myIntent);
 		   return true;
 	   case R.id.Menu_Users:
 		   if (LoginActivity.activeUser.getPermission().equals("Administrator") ||
 			   LoginActivity.activeUser.getPermission().equals("admin"))
 		   {
 			   myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.EditUsersAdminActivity");
		       startActivity(myIntent);
 		   }
 		   else
 		   { 			   
 			   Bundle bundle = new Bundle();
		       bundle.putString("SELECTEDUSER", LoginActivity.activeUser.getUserName());
		       myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.Client",
		                             "com.team5.aLife.Client.EditUserActivity");
		       myIntent.putExtras(bundle);
		       startActivityForResult(myIntent,0);
 		   }
		   Log.i("customListView:Options", "Menu:Users");	   
		   return true;
 		   
 	   default: return super.onOptionsItemSelected(item);
 	   }
    } 
    
    //gets called when returning from preferences
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	
    	//  If a user deletes there own credentials they should be logged out of the system.
    	if (resultCode == 1)
    	{
    		finish();
    		Log.i(TAG+"onActivityResult", "Generic User just deleted their login credentials");
    	}
    }
    
    
    // Populate the pop-up menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
 	   MenuInflater inflater = getMenuInflater();
 	   inflater.inflate(R.layout.devicemenu, menu);
 	   return true;
    }
           
    class DeviceAdapter extends ArrayAdapter<Device> {

        private ArrayList<Device> items;

        public DeviceAdapter(Context context, int textViewResourceId, ArrayList<Device> items) {
        		// Constructor for super class ArrayAdapter
                super(context, textViewResourceId, items);
                this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        	
        		Log.i(TAG+"getView", "I am in view updating listrow");
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.listviewrow, null);
                }
                Device o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.RowDeviceName);
                        TextView bt = (TextView) v.findViewById(R.id.RowZigbeeStatus);
                        ImageView icon = (ImageView) v.findViewById(R.id.icon);
                        if (tt != null) {
                              tt.setText(o.getDeviceName());                            }
                        if(bt != null){
                        	if (o.getZigbeeStatus() ==1 )
                        	{
                              bt.setText("Available");
                        	  bt.setTextColor(Color.GREEN);
                        	}
                        	else
                        	{
                        	  bt.setText("Unavailable");
                        	  bt.setTextColor(Color.RED);
                        	}
                        }
                        if (icon != null) {
                        	icon.setImageResource(o.getDeviceIcon());
                        }
                }
                return v;
        }
        

    } // End Device Adapter
} // end customListView