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.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.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.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gson.Gson;

public class EditUsersAdminActivity extends ListActivity{
	
	private final String TAG = "EditUserAdminActivity:  ";
	
	private final int CONTEXT_MENU_EDIT_INFO   = 1;
	private final int CONTEXT_MENU_DELETE_USER = 2;
	private final int MENU_ADD_USER            = 3;
	
	protected static User selectedUser;
	
	private ProgressDialog m_ProgressDialog = null; 	// progress dialog
    private ArrayList<User> userList = null;			// holds our device list
    private DeviceAdapter dAdapter;						// custom class that extends ArrayAdapter
	
    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.devicelist);
        
        registerForContextMenu(getListView());
        
        userList = new ArrayList<User>();			// create a new array of devices
        // Create the row adapter for the ListView        
        dAdapter = new DeviceAdapter(this, R.layout.listviewrow, userList);
        // Set the ROW adapter for the ListView
        setListAdapter(dAdapter);
        // Bind the Device selection

        // Get the device list from the server in JSON format
        refreshUsers();
                
    } // end onCreate
    
    public void onResume()
    {
    	super.onResume();
    	refreshUsers();
    }
    
    private void refreshUsers(){
    	// Since this is a network action show the progress dialog
        m_ProgressDialog = ProgressDialog.show(EditUsersAdminActivity.this,    
                "Please wait...", "Retrieving data ...", true);
        
        // reset the device list to empty
        userList.clear();
        
        String replyString = socketDispatch.instance().sendReceive(new GetAllUsersRequest());        
        
        // Strip off the 102& header
        replyString = replyString.substring(4, replyString.length());
        
        // reset the device list to empty
        userList.clear();
        
        // If there was a response then turn it into
        // an ArrayList<Device> for the ListView
        if (replyString != null){
        	userList = parseResponse.instance().toArrayListUser(replyString);
            Log.i(TAG + "refreshDevices", "deviceList has " + userList.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(userList != null && userList.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 " + userList.size());
                for(int i=0; i< userList.size(); i++)
                {
                	dAdapter.add(userList.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);
      
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
      menu.setHeaderTitle("Options");
      if (userList.get((int)info.id).getUserID() == LoginActivity.activeUser.getUserID())
    	  menu.add(0, CONTEXT_MENU_EDIT_INFO, 0, "Edit Info");
      else
    	  menu.add(0, CONTEXT_MENU_DELETE_USER, 0, "Delete User");
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      switch (item.getItemId()) {
      case CONTEXT_MENU_EDIT_INFO:
    	selectedUser = userList.get((int)info.id);
    	Bundle bundle = new Bundle();
        bundle.putString("SELECTEDUSER", selectedUser.getUserName());
    	myIntent = new Intent();
		myIntent.setClassName("com.team5.aLife.Client",
                              "com.team5.aLife.Client.EditUserActivity");
		myIntent.putExtras(bundle);
        startActivity(myIntent);
        Log.i(TAG+"onContextItemSelected", "I clicked on id " + info.id);
        selectedUser = null;
        return true;
        
      case CONTEXT_MENU_DELETE_USER:
      selectedUser = userList.get((int)info.id);
      Log.i(TAG+"onContextItemSelected", "User's name is " + selectedUser.getUserName());
      
      AlertDialog.Builder builder = new AlertDialog.Builder(EditUsersAdminActivity.this);
  			builder.setTitle("Delete User")
  		   .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 DeleteUserRequest(selectedUser));
        	   
  	        	   Log.i(TAG+"OnClick", replyString);
  	        	   
  	        	   String[] tokens = replyString.split(delimiter);
           
  	        	   TransactionReply deleteUserReply = gson.fromJson(tokens[1], TransactionReply.class);

  	        	   displayDeleteUserResult(deleteUserReply.wasTransactionSuccessful());
  	        	   
  	        	   refreshUsers();
  	        	 
  	        	   selectedUser = null;
  	           }
  	       })
  	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
  	           public void onClick(DialogInterface dialog, int id) 
  	           {
  	                dialog.cancel();
  	           }
  	       });
  			builder.show();
      
      Log.i(TAG+"onContextItemSelected", "I clicked on id " + info.id);
      return true;
      default:
        return super.onContextItemSelected(item);
      }
    }
    
    public void displayDeleteUserResult(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();
        }
    }
    
 // Handle menu selections
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
 	   // Handle menu item selection
 	   switch (item.getItemId()){
 	   
 	   case MENU_ADD_USER:
 		   myIntent = new Intent();
 		   myIntent.setClassName("com.team5.aLife.Client",
 	                             "com.team5.aLife.Client.AddUserActivity");
 	       startActivity(myIntent);
 		   Log.i("customListView:Options", "Menu:Refresh List");
 		   return true;	   
 	   default: return super.onOptionsItemSelected(item);
 	   }
    } 
    
    
    // Populate the pop-up menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	menu.add(0, MENU_ADD_USER, 0, "AddUser");
 	   return true;
    }
    
    class DeviceAdapter extends ArrayAdapter<User> {

        private ArrayList<User> items;

        public DeviceAdapter(Context context, int textViewResourceId, ArrayList<User> 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);
                }
                User user = items.get(position);
                if (user != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView tr = (TextView) v.findViewById(R.id.RowDeviceName);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        TextView br = (TextView) v.findViewById(R.id.RowZigbeeStatus);
                        ImageView icon = (ImageView) v.findViewById(R.id.icon);
                        if (tt != null) {
                              tt.setText("User Name: ");                            
                        }
                        if (tr != null){
                        	  tr.setText(user.getUserName());
                        }
                        if(bt != null){
                              bt.setText("Access Level: ");
                        }
                        if(br != null){
                        	  br.setText(user.getPermission());
                        	  if (user.getPermission().equals("Administrator"))
                        		  br.setTextColor(Color.GREEN);
                        	  else
                        		  br.setTextColor(Color.RED);
                        }
                        if (icon != null) {
                        	icon.setImageResource(R.drawable.icon);
                        }
                }
                return v;
        }
        

    } // End Device Adapter

}


