package com.team5.aLife.BaseStation;

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;

import com.team5.aLife.BaseStation.DBHandler.DB_Devices;

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 DBHandler db = new DBHandler(this);			// database handler object

    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.BaseStation",
		                             "com.team5.aLife.BaseStation.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.BaseStation",
		                             "com.team5.aLife.BaseStation.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.BaseStation",
		                             "com.team5.aLife.BaseStation.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.BaseStation",
		                             "com.team5.aLife.BaseStation.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(DeviceListActivity.this,    
                "Please wait...", "Retrieving data ...", true);
        
        // reset the device list to empty
        deviceList.clear();
        
        // Holds all the devices
    	Device tempDevice;
    	
    	db.open();
    	
    	Cursor c = db.getAllDevices();
    	
    	/* Get the indices of the Columns we will need */
        int IDCol = c.getColumnIndex(DB_Devices._ID);
        int deviceTypeCol = c.getColumnIndex(DB_Devices.DEVICE_TYPE);
        int nameCol = c.getColumnIndex(DB_Devices.NAME);
        int addressCol = c.getColumnIndex(DB_Devices.ADDRESS);
        int zigbeeStatusCol = c.getColumnIndex(DB_Devices.ZIGBEE_STATUS);
        int statusCol = c.getColumnIndex(DB_Devices.STATUS);
        int updatedTimeCol = c.getColumnIndex(DB_Devices.UPDATED_TIME);
        
        // Check if our result was valid. 
        if (c != null) {
        	
                // Check if at least one Result was returned. 
                if (c.moveToFirst()) 
                {	
                	do {
                        //  Retrieve the values of the Entry the Cursor is pointing to. 
                        int ID = c.getInt(IDCol);
                        int deviceType = c.getInt(deviceTypeCol);
                        String name = c.getString(nameCol);
                        String address = c.getString(addressCol);
                        int zigbeeStatus = c.getInt(zigbeeStatusCol);
                        int status = c.getInt(statusCol);
                        int updatedTime = c.getInt(updatedTimeCol);
                        
                        tempDevice = new Device(ID, deviceType, name, address,
                        							   zigbeeStatus, status);
                        
                        tempDevice.setUpdatedTime(updatedTime);
                        
                        deviceList.add(tempDevice);
                        
                	} while (c.moveToNext());
                	
                }
        }
    	
        c.close();
    	db.close(); 
        
        // Turn off the progess dialog
        m_ProgressDialog.dismiss();
        
        // Let the ListView know there is new data to display
        Log.i(TAG+"refreshDevices", "I have " + deviceList.size() + " devices.  About to call updateListView");
        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.BaseStation",
                              "com.team5.aLife.BaseStation.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.BaseStation",
                                 "com.team5.aLife.BaseStation.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.BaseStation",
                                 "com.team5.aLife.BaseStation.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.BaseStation",
		                             "com.team5.aLife.BaseStation.EditUsersAdminActivity");
		       startActivity(myIntent);
 		   }
 		   else
 		   { 			   
 			   Bundle bundle = new Bundle();
		       bundle.putString("SELECTEDUSER", LoginActivity.activeUser.getUserName());
		       myIntent = new Intent();
		       myIntent.setClassName("com.team5.aLife.BaseStation",
		                             "com.team5.aLife.BaseStation.EditUserActivity");
		       myIntent.putExtras(bundle);
		       startActivityForResult(myIntent,0);
 		   }
		   Log.i("customListView:Options", "Menu:Users");	   
		   return true;
		   
	   case R.id.Menu_Preferences:
 		   myIntent = new Intent();
  		   myIntent.setClassName("com.team5.aLife.BaseStation",
                                 "com.team5.aLife.BaseStation.PreferencesActivity");
           startActivity(myIntent);
		   Log.i("customListView:Options", "Menu:Preferences");
		   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) {
                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
