package com.beem.project.beem;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.beem.project.beem.jingle.JingleService;
import com.beem.project.beem.service.XmppConnectionAdapter;
import com.beem.project.beem.service.XmppFacade;
import com.beem.project.beem.service.aidl.IXmppFacade;

/**
 * This class is for the Beem service. The connection to the xmpp server will be made asynchronously when the service
 * will start.
 * @author darisk
 */
public class BeemService extends Service {

    /**
     * The id to use for status notification.
     */
    public static final int NOTIFICATION_STATUS_ID = 100;

    private NotificationManager mNotificationManager;
    private XmppConnectionAdapter mConnection;
    private JingleService mJingle;
    private SharedPreferences mSettings;
    private String mLogin;
    private String mPassword;
    private String mHost;
    private String mService;
    private int mPort;
    private ConnectionConfiguration mConnectionConfiguration;
    private ProxyInfo mProxyInfo;
    private boolean mUseProxy;
    private IXmppFacade.Stub mBind;

    /**
     * Constructor.
     */
    public BeemService() {
    }

    /**
     * Close the connection to the xmpp server.
     */
    private void closeConnection() {
	if (mConnection != null)
	    mConnection.disconnect();
    }

    /**
     * Initialise la configuration de la connexion.
     */
    private void initConnectionConfig() {
	java.security.Security.addProvider(new com.sun.security.sasl.Provider());
	mUseProxy = mSettings.getBoolean(getString(R.string.settings_key_proxy_use), false);
	if (mUseProxy) {
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.proxy_types,
		android.R.layout.simple_spinner_item);
	    int pos = mSettings.getInt(getString(R.string.settings_key_proxy_type), 0);
	    String stype = adapter.getItem(pos).toString();
	    String phost = mSettings.getString(getString(R.string.settings_key_proxy_server), "");
	    String puser = mSettings.getString(getString(R.string.settings_key_proxy_username), "");
	    String ppass = mSettings.getString(getString(R.string.settings_key_proxy_password), "");
	    int pport = Integer.parseInt(mSettings.getString(getString(R.string.settings_key_proxy_port), "1080"));
	    ProxyInfo.ProxyType type = ProxyType.valueOf(stype);
	    mProxyInfo = new ProxyInfo(type, phost, pport, puser, ppass);
	    if (mService != null)
		mConnectionConfiguration = new ConnectionConfiguration(mHost, mPort, mService, mProxyInfo);
	    else
		mConnectionConfiguration = new ConnectionConfiguration(mHost, mPort, mProxyInfo);
	} else {
	    if (mService != null)
		mConnectionConfiguration = new ConnectionConfiguration(mHost, mPort, mService);
	    else
		mConnectionConfiguration = new ConnectionConfiguration(mHost, mPort);
	}
	if (mSettings.getBoolean(getString(R.string.settings_key_xmpp_tls_use), false)) {
	    mConnectionConfiguration.setSecurityMode(SecurityMode.required);
	}
	mConnectionConfiguration.setDebuggerEnabled(false);
	mConnectionConfiguration.setSendPresence(true);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IBinder onBind(Intent intent) {
	Log.e("BEEMSERVICE", "ONBIND()");
	return mBind;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate() {

	super.onCreate();
	mSettings = getSharedPreferences(getString(R.string.settings_filename), MODE_PRIVATE);
	mLogin = mSettings.getString(getString(R.string.settings_key_account_username), "");
	mPassword = mSettings.getString(getString(R.string.settings_key_account_password), "");
	mHost = mSettings.getString(getString(R.string.settings_key_xmpp_server), "");
	mPort = Integer.parseInt(mSettings.getString(getString(R.string.settings_key_xmpp_port), "5222"));

	/*
	 * Gestion pour gmail.
	 */
	if ("".equals(mHost)) {
	    mHost = StringUtils.parseServer(mLogin);
	    mService = null;
	    mLogin = StringUtils.parseName(mLogin);
	} else
	    mService = StringUtils.parseServer(mLogin);
	initConnectionConfig();
	mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	mConnection = new XmppConnectionAdapter(mConnectionConfiguration, mLogin, mPassword, this);
	
	Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
	mBind = new XmppFacade(mConnection, this, mJingle);
	mJingle = new JingleService(mConnection.getAdaptee());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onDestroy() {
	super.onDestroy();
	closeConnection();
	mNotificationManager.cancel(NOTIFICATION_STATUS_ID);
	Log.e("BEEEMSERVICE", "ONDESTROY");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onStart(Intent intent, int startId) {
	super.onStart(intent, startId);
	try {
	    mConnection.connectAsync();
	} catch (RemoteException e) {
	    e.printStackTrace();
	}
    }

    /**
     * Show a notification.
     * @param id the id of the notification.
     * @param notif the notification to show
     */
    public void sendNotification(int id, Notification notif) {
	mNotificationManager.notify(id, notif);
    }

    /**
     * Reset the status to online after a deconnection.
     */
    public void resetStatus() {
	Editor edit = mSettings.edit();
	edit.putInt(getString(R.string.PreferenceStatus), 1);
	edit.commit();
    }

    public void initJingle(XMPPConnection adaptee) {
	mJingle.initWhenConntected(adaptee);
	
    }

}
