package com.team5.aLife.BaseStation;

import java.util.ArrayList;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditUserActivity extends Activity {
	
	private User user = null;
	
	private Button update, delete;
	
	private EditText userName, oldPassword, newPassword, confirmPassword;
	
	private DBHandler db = new DBHandler(this);			// database handler object

	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edituser);
        
        update = (Button)findViewById(R.id.Update2);
        delete = (Button)findViewById(R.id.DeleteUser);
        userName = (EditText) findViewById(R.id.UserName2);
        oldPassword = (EditText) findViewById(R.id.OldPassword);
        newPassword = (EditText) findViewById(R.id.NewPassword);
        confirmPassword = (EditText) findViewById(R.id.ReenterPassword2);
        
        String value = "";
    	
    	Bundle extras = getIntent().getExtras();
    	if(extras !=null)
    	{
    		value = extras.getString("SELECTEDUSER");
    	}
        
    	db.open();
    	
    	Cursor c = db.getUser(value);
    	
    	/* 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()) {
                	
                    //  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);
                    
                	user = new User(userID, userName, password, 
                						  permission, failedLogin, timeout, timeoutTime);
                    	
                    	  
                }
        }
    	
        db.close();
        
        if (user != null)
        	userName.setText(user.getUserName());
        
        //  Loads LTF on click and stores spinner selection in bundle to pass to new activity
		update.setOnClickListener(updateListener);
		
		//  Loads LTF on click and stores spinner selection in bundle to pass to new activity
		delete.setOnClickListener(deleteListener);
                
    } // end onCreate
    
    private View.OnClickListener updateListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        
        if (user.getPassword().equals(oldPassword.getText().toString()))
        {
        	if (newPassword.getText().toString().equals(confirmPassword.getText().toString()))
        	{	
            	db.open();
            	
            	db.updateUser(user.getUserID(),
            				  userName.getText().toString(), 
            				  newPassword.getText().toString(), 
            				  user.getPermission(), 
            				  user.getFailedLogin(), 
            				  user.getTimeout(), 
            				  user.getTimeoutTime());
            	
            	db.close();
            	finish();
        	}
        	else
        	{
        		//  Alert the user the new password and confirm password boxes don't match
        		AlertDialog.Builder builder = new AlertDialog.Builder(EditUserActivity.this);
            	builder.setMessage("The passwords do not match")
            	       .setCancelable(false)
            	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   //RegisterDeviceActivity.this.finish();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	alert.show();
        	}
        	
        }
        else
        {
        	//  Alert the user the OldPassword field is incorrect                        	
        	AlertDialog.Builder builder = new AlertDialog.Builder(EditUserActivity.this);
        	builder.setMessage("The old password is incorrect")
        	       .setCancelable(false)
        	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   //RegisterDeviceActivity.this.finish();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
        }
            
        }
    };
    
    private View.OnClickListener deleteListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	AlertDialog.Builder builder = new AlertDialog.Builder(EditUserActivity.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();
	    	   	        
		    	   	       db.deleteUser(user.getUserName());
		    	   	        
		    	   	       db.close();
	    	        	   
		    	   	       setResult(1);
	    	        	   finish();
	    	           }
	    	       })
	    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) 
	    	           {
	    	                dialog.cancel();
	    	           }
	    	       });
	    	builder.show();
            
        }
    };
    
	
}
