package com.team5.aLife.Client;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

public class LoginActivity extends Activity {
	
	String bundleValue;
	
    private EditText te_serverIP, te_port, te_userName, te_password;
	private Button connectButton;
	
	protected static InetAddress serverAddress;
	protected static int serverPort;
	protected boolean socketInuse = true;
	protected boolean pushServiceStarted = false;
	
	private ProgressDialog progressDialog = null;
	
	static private String userName, password;
	
	public static User activeUser;
	
	private final String tag = "aLife";
//	private Boolean connected = false;
//	private Boolean startConnection = false;
	
//	private Timer timer = new Timer();
	
//	private User user;
	
	//private socketDispatch = new dispatcher();
	
	private Gson gsonIn = new Gson();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        
        bundleValue = "";
    	
    	Bundle extras = getIntent().getExtras();
    	if(extras !=null)
    	{
    		bundleValue = extras.getString("details");
    	}
        
        // Get the EditText id's
        te_serverIP = (EditText) findViewById(R.id.ServerIP);
        te_port = (EditText) findViewById(R.id.ServerPORT);
        te_userName = (EditText) findViewById(R.id.UserID);
        te_password = (EditText) findViewById(R.id.Password);
        
        // Get the Button id's
        connectButton = (Button) findViewById(R.id.Login);
        connectButton.setOnClickListener(loginListener);
        //startPushServiceButton = (Button) findViewById(R.id.start_button);
        //startPushServiceButton.setOnClickListener(startPushServiceListener);
        
        //stopPushServiceButton = (Button) findViewById(R.id.stop_button);
        //stopPushServiceButton.setOnClickListener(stopPushServiceListener);
        
//        te_serverIP.setText("70.46.155.74"); 
//        te_serverIP.setText("10.36.48.170");
        te_serverIP.setText("192.168.1.102");
        te_port.setText("8640");
//        te_port.setText("4444");
        te_userName.setText("Tim");
        // te_password.setHint("password");
        // TODO Make password input hidden
        te_password.setText("password");
        
        // TODO Make the IP address and Port number a history input
        
        // TODO Make "login" button change to connected


               
    } // end onCreate
   @Override
 protected void onStart(){
	   super.onStart();   
   	    	
} // end onStart()
   
   @Override
 protected void onDestroy(){
	 super.onDestroy();
	 
	 
	 stopPushService();
	 // TODO aLife:onDestroy
//	 stopListener();
	 
 } // end onDestroy
  
//    public void startListener() {
//    	Log.d("aLife:startListener", "Starting aLifeListener");
//    	startService(new Intent(this, aLifeListener.class));
//    }
    
//    public void stopListener() {
//    	if (timer != null)
//    		timer.cancel();
//    	Log.d("aLife:stopListener", "Timer Stopped");
//    }
    private boolean login(){
		// These 4 booleans are used to verify all the TextEdit
		// fields have an valid entry before attempting a connection.
		// When all 4 are true then a connection attempt will be made
		// and the username/password combo will be checked at the
		// server
		Boolean ipValid = false;
		Boolean portValid = false;
		Boolean passwordValid = false;
		Boolean usernameValid = false;
		
		// make sure a we don't allow and old IP address to sneak through
		serverAddress = null;
		
//		socketDispatch.instance().send("test");
//		String responce = socketDispatch.instance().sendReceive("Test SR");
		
		if (true){
			
			// Verify valid port number
			// if (te_port.hasSelection()) // this didn't respond to a filled TextEdit
				// TODO See what happens if Integer.parseInt fails w/ an invalid Port #
				serverPort = Integer.parseInt(te_port.getText().toString());
			// TODO Narrow down valid port number range
			if (serverPort > 1024 && serverPort < 65565)
				portValid = true;			
			
			// Verify valid IP address
			// if (te_serverIP.hasSelection()){  // try/catch sufficient replacement for if?
			try {
				String s = te_serverIP.getText().toString();
				// Log.d("aLife", "to_serverIP.toString() = " + s);					
				if (s != null)
					serverAddress = InetAddress.getByName(s);		// requires try/catch
				if (serverAddress != null)
					ipValid = true;
			} catch (UnknownHostException e) {
				makeToast("Enter a valid IP address");
				Log.e("aLife", "te_serverIP.toString failed",e);
			}
			// } end if
			
			// Verify username field
			userName = te_userName.getText().toString();
			if (userName == null){
				makeToast("Enter a username");
			} else {
				usernameValid = true;
			}
				
			// Verify password field
			password = te_password.getText().toString();
			if (password == null){
				makeToast("Enter a password");
			} else {
				passwordValid = true;
			}
			
			// If all data is complete and valid then start the 
			// listener thread!
			if (portValid && ipValid && usernameValid && passwordValid){
				// Attempt a connection
//				makeShortToast("Connecting...");
				Log.d("aLife:Login", "Login pressed: portValid:" + portValid +
						" ipValid:" + ipValid +
						" userNameValid:" + usernameValid +
						" passwordValid:" + passwordValid);
				
				progressDialog = ProgressDialog.show(this, 
						"Please wait...", "Logging in...", true);
				
				LoginRequest lr = new LoginRequest(userName, password);
				String reply = socketDispatch.instance().login(lr);
				
				if (reply.equals("Could Not Connect")){
					progressDialog.dismiss();
					showAlert("Could Not Connect To Server");
					return false;
				}
				
				if (reply.equals("Did Not Receive Response")){
					progressDialog.dismiss();
					showAlert("Did not receive Responce from server");
					return false;
				}
				
				if (parseLoginResponse(reply)){
					// Good Login
					// Turn off progress bar
					progressDialog.dismiss();
					return true;
				} else {
					// Bad Login
					// Turn off progress bar
					progressDialog.dismiss();
					// Display error popup
					
	                 //  Alert the user the Password field is incorrect                        	
					showAlert("Login Failed");
					return false;
				}
					
				
//				startConnection = true;
//				startService(new Intent(this, aLifeListener.class));
				
//		    	timer.schedule(new TimerTask(){
//		    		public void run(){
//		    			Log.d("aLife:ButtonListener", "timer.schedule(new TimerTask()");
//		    			startListener();
//		    			}
//		    		}, 1000);
			
				
			// this.getClass().getClassLoader()	
				
			} else {
				makeToast("Enter valid data for all fields");
				Log.d("aLife", "Login pressed but portValid:" + portValid +
						" ipValid:" + ipValid +
						" userNameValid:" + usernameValid +
						" passwordValid:" + passwordValid);
			}						
		} // end while(true)
		
		return false;
    } // end Login()
 
    private boolean parseLoginResponse(String s){
    	String rcvd[] = new String[1];
    	String delimiter = "[&]+";
    	rcvd = s.split(delimiter);
    	
    	switch (Integer.parseInt(rcvd[0])){
    	case 101:
    		LoginReply lr;
    		Log.i(tag + ":parseLoginResponse", "Received Login Response");
    		lr = (LoginReply) gsonIn.fromJson(rcvd[1], LoginReply.class);
    		if (lr.wasLoginSuccesful())
    		{
    			activeUser = lr.getUser();
    			startPushService();
    			return true;
    		}
    		else
    			return false;
    		
    	}
    	return false;
    }
    
    private void showAlert(String s){
       	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage(s)
    	       .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 loginListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
		if (login()){
			   // Call the Device List Activity
			   Intent deviceIntent = new Intent();
			   if (bundleValue != null && bundleValue.equals("Garage"))
				   deviceIntent.setClassName("com.team5.aLife.Client", "com.team5.aLife.Client.WirelessSensorActivity");
			   else if (bundleValue != null && bundleValue.equals("Power"))
				   deviceIntent.setClassName("com.team5.aLife.Client", "com.team5.aLife.Client.WirelessPowerSwitchActivity");
			   else
				   deviceIntent.setClassName("com.team5.aLife.Client", "com.team5.aLife.Client.DeviceListActivity");
			   startActivity(deviceIntent);
		}
 
		} // end onClick()
	}; // end loginListener
    
    private View.OnClickListener startPushServiceListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			startPushService();
		}
	};
	
	private View.OnClickListener stopPushServiceListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			stopPushService();
		}
	};
    	
	private void startPushService(){
		// TODO Copied from Tokudu PushActivity.java - Rewrite!
    	Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
//    	editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
    	editor.putString(PushService.PREF_DEVICE_ID, "HD2");
    	editor.commit();
		PushService.actionStart(getApplicationContext());
		pushServiceStarted = true;
  		//startPushServiceButton.setEnabled(false);
  		//stopPushServiceButton.setEnabled(true);
	}
	
	private void stopPushService(){
		// TODO Copied from Tokudu PushActivity.java - Rewrite!
		if (pushServiceStarted)
			PushService.actionStop(getApplicationContext());		        								
  		//startPushServiceButton.setEnabled(true);
  		//stopPushServiceButton.setEnabled(false);
	}
	
    public void makeToast(String string) {
    	Toast.makeText(this, string, Toast.LENGTH_LONG).show();
    }

    public void makeShortToast(String string) {
    	Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }
    
    // Required to pass data to aLifeListener service
    // TODO Tim says this data should be packaged in a "bundle" and pasted with the Intent 
    public static InetSocketAddress getServerAddress (){
		return new InetSocketAddress(serverAddress, serverPort);
    	
    }
    
    public static String getUserName(){
    	return userName;
    }
    
}