package com.team5.aLife.Client;

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

import com.google.gson.Gson;

public class EditUserActivity extends Activity {
	
	private User user = null;
	
	private Button update, delete;
	
	private EditText userName, oldPassword, newPassword, confirmPassword;
	
	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.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");
    	}
        
    	String replyString = socketDispatch.instance().sendReceive(new GetUserRequest(value));
    	
    	String[] tokens = replyString.split(delimiter);
        
   	    LoginReply userReply = gson.fromJson(tokens[1], LoginReply.class);    	
    	
   	    user = userReply.getUser();
        
        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()))
        	{	
        		user.setUserName(userName.getText().toString());
        		user.setPassword(newPassword.getText().toString());
        		
        		String replyString = socketDispatch.instance().sendReceive(new UpdateUserRequest(user));
        		
        		String[] tokens = replyString.split(delimiter);
        		
        		TransactionReply updateUserReply = gson.fromJson(tokens[1], TransactionReply.class);
        		
        		if (updateUserReply.wasTransactionSuccessful())
                {
                	AlertDialog.Builder builder = new AlertDialog.Builder(EditUserActivity.this);
                	builder.setMessage("Transaction Successful")
                	       .setCancelable(false)
                	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                	           public void onClick(DialogInterface dialog, int id) {
                	        	   //RegisterDeviceActivity.this.finish();
                	        	   finish();
                	           }
                	       });
                	AlertDialog alert = builder.create();
                	alert.show();
                }
                else
                {
                	AlertDialog.Builder builder = new AlertDialog.Builder(EditUserActivity.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();
                }
        	}
        	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) 
	    	           {
	    	        	   String replyString = socketDispatch.instance().sendReceive(new DeleteUserRequest(user));
	    	        	   
	      	        	   String[] tokens = replyString.split(delimiter);
	               
	      	        	   TransactionReply deleteUserReply = gson.fromJson(tokens[1], TransactionReply.class);

	      	        	   displayDeleteUserResult(deleteUserReply.wasTransactionSuccessful());
	    	        	   
		    	   	       setResult(1);
	    	        	   finish();
	    	           }
	    	       })
	    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) 
	    	           {
	    	                dialog.cancel();
	    	           }
	    	       });
	    	builder.show();
            
        }
    };
    
    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();
        }
    }
}
