package com.team5.aLife.BaseStation;

import java.util.ArrayList;

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

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

public class NotificationActivity extends ListActivity {
	
	// TODO: See http://stackoverflow.com/questions/3044049/android-listview-onclick-event-in-the-tabs for the FLIPPER???
	
    private static final String TAG = "NotificationActivity:  ";
    private final int CONTEXT_MENU_DELETE_NOTIFICATION = 1;
    
    private final int REFRESH = 1;
    
    private ALifeNotificationSetup selectedNotification = null;
    private ProgressDialog m_ProgressDialog = null; 					// progress dialog
    private ArrayList<ALifeNotificationSetup> notificationList = null;		// holds our device list
    private NotificationAdapter dAdapter;										// custom class that extends ArrayAdapter
    private DBHandler db = new DBHandler(this);							// database handler object

    private Intent myIntent;
    
    private final String delimiter = "[&]+";
    
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
        
        registerForContextMenu(getListView());
        
        notificationList = new ArrayList<ALifeNotificationSetup>();			// create a new array of devices
        // Create the row adapter for the ListView        
        this.dAdapter = new NotificationAdapter(this, R.layout.listviewrow, notificationList);
        // Set the ROW adapter for the ListView
        setListAdapter(this.dAdapter);
        // Bind the Device selection

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

	protected void onListItemClick(ListView l, View v, int position, long id){
		
		selectedNotification = notificationList.get(position);
		
		switch (getDeviceType(selectedNotification.getDeviceID())){	   
	 	   case Device.DEVICE_TYPE_THERMOSTAT:
	 		   Log.i(TAG + "onListItemClick", "Selected a thermostat");
	 		   
	 		   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.NotificationPowerActivity");
		       startActivity(myIntent);
	 		   break;
	 	  case Device.DEVICE_TYPE_SWITCH:
	 		   Log.i(TAG + "onListItemClick", "Selected a switch device");
	 		   
	 		   break;
	 	  case Device.DEVICE_TYPE_WIRELESS_SENSOR:
	 		   Log.i(TAG + "onListItemClick", "Selected a wireless sensor");
	 		   
	 		   break;
	 	  default: 
	 		   super.onListItemClick(l, v, position, id);
	 	  	   break;
		}
    	
    }

    public void onResume()
    {
    	super.onResume();
    	refreshNotifications();
    }
    
    // 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:
 		   refreshNotifications();
 		   return true;
 	   default: return super.onOptionsItemSelected(item);
 	   }
    }
    
    private void refreshNotifications(){
    	// Since this is a network action show the progress dialog
        m_ProgressDialog = ProgressDialog.show(NotificationActivity.this,    
                "Please wait...", "Retrieving data ...", true);
        
        // reset the device list to empty
        notificationList.clear();
        
        // Holds all the devices
    	
        ALifeNotificationSetup tempNotification;
    	
    	db.open();
    	
    	Cursor c = db.getAllNotificationsForUser(LoginActivity.activeUser.getUserID());
    	
    	/* Get the indices of the Columns we will need */
        int IDCol = c.getColumnIndex(DB_Notifications_Setup._ID);
        int deviceIDCol = c.getColumnIndex(DB_Notifications_Setup.DEVICE_ID);
        int userIDCol = c.getColumnIndex(DB_Notifications_Setup.USER_ID);
        int notificationTypeCol = c.getColumnIndex(DB_Notifications_Setup.NOTIFICATION_TYPE);
        int triggerConditionCol = c.getColumnIndex(DB_Notifications_Setup.TRIGGERING_CONDITION);
        
        if (c != null)
	    	if (c.moveToFirst())
	    	{	
	    		do {
	    		//  Retrieve the values of the Entry the Cursor is pointing to. 
	            int ID = c.getInt(IDCol);
	            int deviceID = c.getInt(deviceIDCol);
	            int userID = c.getInt(userIDCol);
	            int notificationType = c.getInt(notificationTypeCol);
	            String triggeringCondition = c.getString(triggerConditionCol);
	            
	            tempNotification = new ALifeNotificationSetup(ID, deviceID, userID, notificationType, 
	            										  triggeringCondition);
	            
	            notificationList.add(tempNotification);
	            
	    		}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 " + notificationList.size() + " notifications.  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(notificationList != null && notificationList.size() > 0)
//            {
//                dAdapter.notifyDataSetChanged();
//                // Clear all items so they don't start stacking up
//                dAdapter.clear();
//                Log.i(TAG+"updateListView.run()", "notificationList is not null and has size > 0.  notificationList size is " + notificationList.size());
//                for(int i=0; i<notificationList.size(); i++)
//                {
//                	dAdapter.add(notificationList.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");
      menu.add(0, CONTEXT_MENU_DELETE_NOTIFICATION, 0, "Delete Notification");
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
        
        case CONTEXT_MENU_DELETE_NOTIFICATION:
          
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			builder.setTitle("Delete Notification")
    		   .setMessage("All changes are final, do you want to proceed?")
    	       .setCancelable(false)
    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) 
    	           {
    	        	 db.open();
    	           	 
    	        	 db.deleteNotification(notificationList.get((int)info.id).getID());
    	           
    	        	 db.close();
    	        	 
    	        	 startService(new Intent(NotificationActivity.this, BackgroundServices.class));
    	        	 refreshNotifications();
    	           }
    	       })
    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) 
    	           {
    	                dialog.cancel();
    	           }
    	       });
    			builder.show();
        return true;
        default:
          return super.onContextItemSelected(item);
      }
    }
    
           
    class NotificationAdapter extends ArrayAdapter<ALifeNotificationSetup> {

        private ArrayList<ALifeNotificationSetup> items;

        public NotificationAdapter(Context context, int textViewResourceId, ArrayList<ALifeNotificationSetup> 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.listview_row_notification, null);
                }
                ALifeNotificationSetup o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.NotificationDeviceName);
                        TextView bt = (TextView) v.findViewById(R.id.NotificationCondtion);
                        TextView time = (TextView) v.findViewById(R.id.NotificationTime);
                        if (tt != null) {
                              tt.setText(getDeviceName(o.getDeviceID()));                            
                        }
                        if(bt != null){
                        	
                        	int deviceType = getDeviceType(o.getDeviceID());
                        	
                        	if (deviceType == Device.DEVICE_TYPE_POWER_MONITOR_SWITCH )
                        	{
                        		bt.setText("Device is on");
                        	}
                        	else if(deviceType == Device.DEVICE_TYPE_SWITCH )
                        	{
                        		bt.setText("Garage is open");
                        	}
                        	else if(deviceType == Device.DEVICE_TYPE_THERMOSTAT)
                        	{
                        		bt.setText("Outside temperate is 5 deg off");
                        	}
                        	else if(deviceType == Device.DEVICE_TYPE_WIRELESS_SENSOR )
                        	{
                        		bt.setText("Garage is open");
                        	}
                        	
                        }
                        if (time != null) {
                        	time.setText(parseCondtionToString(o.getTriggeringCondition()));
                        }
                }
                return v;
        }
        

    } // End Device Adapter
    
    private int getDeviceType(int deviceID) {
		
		int deviceType = 0;
		
		db.open();
		
		Cursor c = db.getDevice(deviceID);
		
		/* Get the indices of the Columns we will need */
        int deviceTypeCol = c.getColumnIndex(DB_Devices.DEVICE_TYPE);
        
        // Check if our result was valid. 
        if (c != null) {
        	
                // Check if at least one Result was returned. 
                if (c.moveToFirst()) 
                {	
                	
                    //  Retrieve the values of the Entry the Cursor is pointing to. 
                    deviceType = c.getInt(deviceTypeCol);
                	
                }
        }
		
		c.close();
		db.close();
		
		return deviceType;
	}
	private String getDeviceName(int deviceID) {
		
		String deviceName = "";
		
		db.open();
		
		Cursor c = db.getDevice(deviceID);
		
		/* Get the indices of the Columns we will need */
        int deviceNameCol = c.getColumnIndex(DB_Devices.NAME);
        
        // Check if our result was valid. 
        if (c != null) {
        	
                // Check if at least one Result was returned. 
                if (c.moveToFirst()) 
                {	
                	
                    //  Retrieve the values of the Entry the Cursor is pointing to. 
                    deviceName = c.getString(deviceNameCol);
                	
                }
        }
		
		c.close();
		db.close();
		
		return deviceName;
	}

	public String parseCondtionToString(String triggeringCondition) {
		
		
		Log.i(TAG+"parseCondtionToString", "The value of the trigerring condition is: " + triggeringCondition);
		String tokens[] = triggeringCondition.split(delimiter);
		
		String result= "Between " + numberToTimeString(Integer.parseInt(tokens[0])) +
				 " and " + numberToTimeString(Integer.parseInt(tokens[1]));
		
		return result;
	}
	
	public String numberToTimeString(int intTime)
	{
		switch (intTime){
		
		case 0:
			return "12 am";
		case 1:
			return "1 am";
		case 2:
			return "2 am";
		case 3:
			return "3 am";
		case 4:
			return "4 am";
		case 5:
			return "5 am";
		case 6:
			return "6 am";
		case 7:
			return "7 am";
		case 8:
			return "8 am";
		case 9:
			return "9 am";
		case 10:
			return "10 am";
		case 11:
			return "11 am:";
		case 12:
			return "12 pm";
		case 13:
			return "1 pm";
		case 14:
			return "2 pm";
		case 15:
			return "3 pm";
		case 16:
			return "4 pm";
		case 17:
			return "5 pm";
		case 18:
			return "6 pm";
		case 19:
			return "7 pm";
		case 20:
			return "8 pm";
		case 21:
			return "9 pm";
		case 22:
			return "10 pm";
		case 23:
			return "11 pm";
		default:
			return "";
		}
	}
	
} // end customListView
