/**
 * 
 */
package com.beem.project.beem;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.packet.Presence;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.widget.Toast;

import com.beem.project.beem.service.XMPPConnectionAdapter;
import com.beem.project.beem.service.aidl.IXMPPConnection;
import com.beem.project.beem.service.aidl.IXMPPFacade;

/**
 * @author darisk
 * 
 */
public class BeemService extends Service {

    private NotificationManager notificationManager;

    private IXMPPConnection connection;
    private SharedPreferences settings;
    private String login;
    private String password;
    private String host;
    private Set<String> onlineContactList = new HashSet<String>();
    private Roster roster;

    private IXMPPFacade.Stub bind = new IXMPPFacade.Stub() {

	@Override
	public IXMPPConnection getXMPPConnection() throws RemoteException {
	    // TODO Auto-generated method stub
	    return connection;
	}
    };

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent intent) {
	// TODO Auto-generated method stub
	new Thread(connectingThread).start();
	if (IXMPPConnection.class.getName().equals(intent.getAction()))
	    return bind;
	return null;
    }

    @Override
    public void onCreate() {
	super.onCreate();
	settings = getSharedPreferences(getString(R.string.PreferenceFileName),
		MODE_PRIVATE);
	login = settings.getString(getString(R.string.PreferenceLoginKey), "");
	password = settings.getString(
		getString(R.string.PreferencePasswordKey), "");
	host = settings.getString(getString(R.string.PreferenceHostKey), "");
	notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public void onStart(Intent intent, int startId) {
	new Thread(connectingThread).start();
    }

    @Override
    public void onDestroy() {
	closeConnection();
	showBasicNotification(R.string.BeemServiceDestroyed);
    }

    private void showBasicNotification(int stringResource) {
	String text = (String) getText(stringResource);
	Notification notif = new Notification(R.drawable.logo, text, System
		.currentTimeMillis());
	notif.defaults = Notification.DEFAULT_ALL;
	notif.setLatestEventInfo(this, text, text, PendingIntent.getActivity(
		this, 0, new Intent(), 0));
	notificationManager.notify(stringResource, notif);
    }

    private void closeConnection() {
	if (connection != null)
	    try {
		connection.disconnect();
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
    }

    private RosterListener rosterListener = new RosterListener() {

	@Override
	public void presenceChanged(Presence presence) {
	    // TODO Auto-generated method stub
	    String user = presence.getFrom();
	    Presence bestPresence = roster.getPresence(user);
	    if (bestPresence.getType().equals(Presence.Type.available))
		onlineContactList.add(user);
	}

	@Override
	public void entriesUpdated(Collection<String> arg0) {
	    // TODO Auto-generated method stub

	}

	@Override
	public void entriesDeleted(Collection<String> arg0) {
	    // TODO Auto-generated method stub

	}

	@Override
	public void entriesAdded(Collection<String> arg0) {
	    // TODO Auto-generated method stub

	}
    };

    private Runnable connectingThread = new Runnable() {

	@Override
	public void run() {
	    // TODO Auto-generated method stub
	    try {
		// TODO effectuer la connexion dans un thread
		connection = new XMPPConnectionAdapter("10.0.2.2"); // address
								    // du pc
								    // host de
								    // l'emulateur
		connection.connect();
		connection.login(login, password, "BEEM");
		/*
		 * roster = connection.getRoster();
		 * roster.addRosterListener(rosterListener);
		 */
		showBasicNotification(R.string.BeemServiceCreated);
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		Toast toast = Toast.makeText(BeemService.this, "ERREUR " + e.getMessage(),
			Toast.LENGTH_LONG);
		toast.show();
		e.printStackTrace();
	    }
	}
    };
}
