package it.gotoandplay.example.android.BasicConnection;

import it.gotoandplay.example.android.BasicConnection.R;
import it.gotoandplay.smartfoxclient.ISFSEventListener;
import it.gotoandplay.smartfoxclient.SFSEvent;
import it.gotoandplay.smartfoxclient.SmartFoxClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

/**
 * Basic connection to the SmartFoxServer example.
 * 
 * The activity tries to connect to "10.0.2.2"
 * (special alias to your host loopback interface
 * (i.e., 127.0.0.1 on your development machine))
 * and displays a message if the connection is successful.  
 */
public class BasicConnection extends Activity implements ISFSEventListener {
	private SmartFoxClient mSFSClient;
	
    /** 
     * Called when the activity is first created.
     * 
     * Tries to establish connection with the SmartFoxServer.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        //Creates SmartFoxClient instance with debug log enabled.
        final SmartFoxClient sfs = new SmartFoxClient(true);
        mSFSClient = sfs;
        //Adds the connection listener.
        //In this simple example the activity implements the ISFSEventListener
        //interface and handles the SFS related events.
        sfs.addEventListener(SFSEvent.onConnection, this);
       	
        //connect() method is called in separate thread
        //so it does not blocks the UI
		new Thread() {
			@Override
			public void run() {
		        sfs.connect("10.0.2.2");
			}
		}.start();
	}

    /**
     * Handles the onConnection event.
     */
	public void handleEvent(final SFSEvent event) {
		//The android UI is not thread safe.
		//The handleEvent event method is NOT called from the UI thread so
		//we create a runnable that runs on the UI thread. 
		runOnUiThread(new Runnable() {
			public void run() {
				if(event.getName().equals(SFSEvent.onConnection)) {
		        	//Gets the text view that shows the connection status message.
					TextView textView = (TextView)findViewById(R.id.txtConnectionStatus);
					//Checks if the connection is successful or not
					//and displays the corresponding message.
					if(event.getParams().getBool("success")) {
						textView.setText(R.string.connect_success);
					} else {
						textView.setText(R.string.connect_failed);
					}
				}
			}
		});
	}
	
	/**
	 * Frees the resources.
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if(mSFSClient != null) {
			mSFSClient.removeEventListener(SFSEvent.onConnection, this);
			mSFSClient.disconnect();
		}
		
		//Exiting with System.exit(0) to avoid problem with persisting MINA threads
		System.exit(0);
	}
}