package com.team5.aLife.BaseStation;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
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;

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

public class LoginActivity extends Activity {
	
	private Button login, register;
	
	private EditText userID, passwordText;
	
	private DBHandler db = new DBHandler(this);
	
	public static User activeUser;
	
	public static Context myContext;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myContext = this;
        
        PreferenceHandler.init(this);
        
        //PreferenceHandler.unregisterDevice();
        PreferenceHandler.loadDefaultPreferences();
        PreferenceHandler.updatePreferences();
        
        if (PreferenceHandler.isDeviceRegistered())
        {
        	setContentView(R.layout.login);
        	
        	startService(new Intent(this, BackgroundServices.class));
            
            login = (Button) findViewById(R.id.Login);
            userID = (EditText) findViewById(R.id.UserID);
            passwordText = (EditText) findViewById(R.id.Password);
            
            userID.setText("Tim");
            passwordText.setText("password");
            
            login.setOnClickListener(connectListener);
        }
        else
        {

        	setContentView(R.layout.register);
        	
        	register = (Button) findViewById(R.id.Register);
        	
        	register.setOnClickListener(connectListener2);
        }
        
    }
    
    @Override
    public void onDestroy() {
        // Cancel the persistent notification.
        super.onDestroy();
        
        db.close();
        stopService(new Intent(this, BackgroundServices.class));
    }
    
    @Override
    public void onResume() {
        // Cancel the persistent notification.
        super.onResume();
        
        if (userID != null)
        	userID.setText("");
        if (passwordText != null)
        	passwordText.setText("");
    }
    
    private View.OnClickListener connectListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
        	db.open();
        	
        	Cursor c = db.getUser(userID.getText().toString());
        	
        	/* 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);
                        
                        if (passwordText.getText().toString().equals(password))
                        {

                        	activeUser = new User(userID, userName, password, 
                        						  permission, failedLogin, timeout, timeoutTime);
                        	c.close();
                        	db.close();
                        	
                        	Intent myIntent = new Intent();
                    		myIntent.setClassName("com.team5.aLife.BaseStation",
                                                  "com.team5.aLife.BaseStation.DeviceListActivity");
                            startActivity(myIntent);
                        }
                        else
                        {
	                        //  Alert the user the Password field is incorrect                        	
	                    	AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
	                    	builder.setMessage("The incorrect User Name or password")
	                    	       .setCancelable(false)
	                    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	                    	           public void onClick(DialogInterface dialog, int id) {
	                    	        	   //RegisterDeviceActivity.this.finish();
	                    	           }
	                    	       });
	                    	AlertDialog alert = builder.create();
	                    	alert.show();
	                    	
	                    	c.close();
	                    	db.close();
                        }   
                    }
                    else
                    {
                    //  Alert the user the User Name field is incorrect
                    	
                    	AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                    	builder.setMessage("The incorrect User Name or password")
                    	       .setCancelable(false)
                    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    	           public void onClick(DialogInterface dialog, int id) {
                    	        	   //RegisterDeviceActivity.this.finish();
                    	           }
                    	       });
                    	AlertDialog alert = builder.create();
                    	alert.show();
 	
                    	c.close();
                    	db.close();
                    }
            }
            else
            {	
            	//  Alert the user the User Name field is incorrect
            	
            	AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
            	builder.setMessage("The incorrect User Name or password")
            	       .setCancelable(false)
            	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            	           public void onClick(DialogInterface dialog, int id) {
            	        	   //RegisterDeviceActivity.this.finish();
            	           }
            	       });
            	AlertDialog alert = builder.create();
            	alert.show();
            	
            	db.close();
            }
            
        }
    };
    
    private View.OnClickListener connectListener2 = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        	
           
    		Intent myIntent = new Intent();
    		myIntent.setClassName("com.team5.aLife.BaseStation",
                                  "com.team5.aLife.BaseStation.RegisterDeviceActivity");
            startActivity(myIntent);
            finish();
            
        }
    };
}