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.Roster;
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;
import android.widget.EditText;

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;
	private volatile String _parent;
	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, String parent) {
//		Log.d(TAG, "init()");
		_user = user;
		_password = password;
		_host = host;
		_port = port;
		_service = service;
		_parent = parent;
		Thread thread = new Thread() {
			public void run() {
				if (_port > 0){
					init();
				}
			}
		};
		thread.start();
	}
	public synchronized void init() {
		Log.d(TAG, "init()");
		try {
	        _mainService.sendStatus("XMPP設定中");
			fin();

			ConnectionConfiguration config = new ConnectionConfiguration(_host, _port, _service);
			_connection = new XMPPConnection(config);
			_connection.connect();
			_connection.login(_user, _password);
			if (_parent.length() != 0){
				Roster roster = _connection.getRoster();
				String[] groups = {"見守り君"};
				roster.createEntry(_parent, _parent, groups);
			}
			//利用可能(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);
	        _mainService.sendStatus("XMPP接続しました。");
		} catch (Exception e) {
	        _mainService.sendStatus("XMPP設定エラー : " + e.getMessage());
		}
	}
	public void fin(){
		Log.d(TAG, "fin()");
		if ( _connection != null ){
			_connection.disconnect();
			_connection = null;
		}
	}
}
