package jp.ito.camera;

import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

import android.util.Log;

public class XmppService {
	private static final String TAG = XmppService.class.getSimpleName();
	private volatile String _user = null;
	private volatile String _password = null;
	private volatile String _host = null;
	private volatile int _port = -1;
	private volatile String _service;
	XMPPConnection _connection = null;
	MainService _mainService = null;

    //コンストラクタ
    public XmppService(MainService mainService) {
		Log.d(TAG, "XmppService()");
    	_mainService = mainService;

		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			public void run() {
				if (_port > 0){
					init();
				}
			}
		};
		timer.schedule(timerTask, 60*60*1000, 60*60*1000);
    }
	public void init(String user, String password, String host, int port, String service) {
//		Log.d(TAG, "init()");
		_user = user;
		_password = password;
		_host = host;
		_port = port;
		_service = service;
		Thread thread = new Thread() {
			public void run() {
				if (_port > 0){
					init();
				}
			}
		};
		thread.start();
	}
	public synchronized void init() {
		Log.d(TAG, "init()");
		try {
			fin();

			ConnectionConfiguration config = new ConnectionConfiguration(_host, _port, _service);
			_connection = new XMPPConnection(config);
			_connection.connect();
			_connection.login(_user, _password);
			//利用可能(available)である事をサーバに通知
			Presence presence = new Presence(Presence.Type.available);
			_connection.sendPacket(presence);
			PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
			_connection.addPacketListener(new PacketListener() {
				public void processPacket(Packet packet) {
					Message message = (Message) packet;
					String msg = message.getBody();
			        _mainService.sendStatus(msg);
					Log.d(TAG, "recv : " + msg);
				}
			}, filter);
		} catch (Exception e) {
	        _mainService.sendStatus("XMPPのエラー : " + e.getMessage());
		}
	}
	public void fin(){
		Log.d(TAG, "fin()");
		if ( _connection != null ){
			_connection.disconnect();
			_connection = null;
		}
	}
}
