package com.team5.aLife.Client;

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.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.google.gson.Gson;

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
    
    ArrayList<ALifeNotificationSetup> notificationList2;
    
    private Intent myIntent;
    
    private Gson gson = new Gson();
    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
        notificationList2 = new ArrayList<ALifeNotificationSetup>();
        
        
        // 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 (getDevice(selectedNotification.getDeviceID()).getDeviceType()){	   
	 	   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.Client",
		                             "com.team5.aLife.Client.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:
 		   startActivity(new Intent(this, NotificationActivity.class));
 		   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();
        notificationList2.clear();
        dAdapter.clear();
        
        String replyString = socketDispatch.instance().sendReceive(new GetAllNotificationsRequest());        
        
        // Strip off the 102& header
        replyString = replyString.substring(4, replyString.length());
        
        // reset the device list to empty
        //notificationList2.clear();
        
        // If there was a response then turn it into
        // an ArrayList<Device> for the ListView
        if (replyString != null){
        	notificationList2 = parseResponse.instance().toArrayListNotification(replyString);
        	for(int i=0; i<notificationList2.size(); i++)
            {
            	notificationList.add((notificationList2.get(i)));
            	Log.i(TAG+"updateListView.run()", "Iterating through device list " + i);
            }
            Log.i(TAG + "refreshDevices", "deviceList has " + notificationList.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(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<notificationList2.size(); i++)
//                {
//                	notificationList.add((notificationList2.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) 
    	           {
    	        	 
    	        	   String replyString = socketDispatch.instance().sendReceive(new DeleteNotificationRequest(notificationList.get((int)info.id)));
    	        	   
      	        	   String[] tokens = replyString.split(delimiter);
               
      	        	   TransactionReply deleteUserReply = gson.fromJson(tokens[1], TransactionReply.class);

      	        	   displayDeleteNotificationResult(deleteUserReply.wasTransactionSuccessful());
    	        	   
    	        	 
      	        	   socketDispatch.instance().sendReceive(new BackgroundServicesOnStartRequest());
    	        	   refreshNotifications();
    	           }
    	       })
    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) 
    	           {
    	                dialog.cancel();
    	           }
    	       });
    			builder.show();
        return true;
        default:
          return super.onContextItemSelected(item);
      }
    }
    
    public void displayDeleteNotificationResult(boolean result)
    {
    	if (result)
        {
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Transaction Successful")
        	       .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(this);
        	builder.setMessage("Transaction Failed")
        	       .setCancelable(false)
        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   //RegisterDeviceActivity.this.finish();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
        }
    }
    
           
    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);
                Device device = getDevice(o.getDeviceID());
                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(device.getDeviceName());                            
                        }
                        if(bt != null){
                        	
                        	int deviceType = device.getDeviceType();
                        	
                        	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 Device getDevice(int deviceID) {
		
    	
    	String replyString = socketDispatch.instance().sendReceive(new GetDeviceRequest(deviceID));
    	
    	String[] tokens = replyString.split(delimiter);
        
   	    GetDeviceReply getDeviceReply = gson.fromJson(tokens[1], GetDeviceReply.class);
			
		return getDeviceReply.getDevice();
	}
    
	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
