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

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

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 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());
        
        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();
        
        // Holds all the devices
    	User tempUser;
    	
    	db.open();
    	
    	Cursor c = db.getAllUsers();
    	
    	/* Get the indices of the Columns we will need */
        int userIDCol = c.getColumnIndex(DB_Users._ID);
        int userNameCol = c.getColumnIndex(DB_Users.USER_NAME);
        int passwordCol = c.getColumnIndex(DB_Users.PASSWORD);
        int permissionCol = c.getColumnIndex(DB_Users.PERMISSION);
        int failedLoginCol = c.getColumnIndex(DB_Users.FAILED_LOGIN_NUM);
        int timeoutCol = c.getColumnIndex(DB_Users.TIMEOUT);
        int timeoutTimeCol = c.getColumnIndex(DB_Users.TIMEOUT_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 userID = c.getInt(userIDCol);
                        String userName = c.getString(userNameCol);
                        String password = c.getString(passwordCol);
                        String permission = c.getString(permissionCol);
                        int failedLogin = c.getInt(failedLoginCol);
                        int timeout = c.getInt(timeoutCol);
                        int timeoutTime = c.getInt(timeoutTimeCol);
                        
                        tempUser = new User(userID, userName, password, permission,
                        							   failedLogin, timeout, timeoutTime);
                      
                        userList.add(tempUser);
                        
                	} while (c.moveToNext());
                	
                }
        }
    	
    	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 " + userList.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);
      
      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.BaseStation",
                              "com.team5.aLife.BaseStation.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) 
  	           {
  	        	 db.open();
  	           
  	        	 Log.i(TAG+"onContextItemSelected", "User's name is " + selectedUser.getUserName());
  	        	 db.deleteUser(selectedUser.getUserName());
  	           
  	        	 db.close();
  	        	   
  	        	 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);
      }
    }
    
 // 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.BaseStation",
 	                             "com.team5.aLife.BaseStation.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

}


