package com.sample;

import java.io.ByteArrayInputStream;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.w3c.dom.Element;

public class Xmpp {
	private static class XmppHolder {
		/**
		 * インスタンス
		 */
		private static final Xmpp instance = new Xmpp();
	}

	/**
	 * インスタンス取得.
	 * @return インスタンス
	 */
	public static Xmpp getInstance() {
		return XmppHolder.instance;
	}
		
	private Xmpp(){
		doExecute();		
	}
	
	private XMPPConnection connection = null;
	
	/* サーバへの接続とログイン */
	public void connect(String server, String username, String password) {
		try {
			// 接続の設定
			Connection.DEBUG_ENABLED = true;
			SmackConfiguration.setPacketReplyTimeout(5000);
			ConnectionConfiguration config = new ConnectionConfiguration(server);
			config.setSASLAuthenticationEnabled(false);

			// サーバに接続してログインする
			this.connection = new XMPPConnection(config);
			this.connection.connect();
			this.connection.login(username, password);
		} catch (XMPPException ex) {
			ex.printStackTrace();
		}
	}

	/* 接続の終了 */
	public void destroy() {
		this.connection.disconnect();
	}
	
	public void doExecute(){
		// 接続してチャットを開始
		connect("localhost.localdomain", "user01", "user01");

		connection.addPacketListener(new PacketListener() {
			public void processPacket(Packet packet) {
				XmlUtil util = XmlUtil.getInstance();
				Element root = util.parse(new ByteArrayInputStream(packet.toXML().getBytes()));
				String id = util.getId(root);
				String xxx = packet.toXML();
				if (id == null){
					System.out.println("none" + "\tSample\trecv\telse");
					return;
				}
			
				System.out.println(id + "\tSample\trecv\tstart");
				HttpUtil httpUtil = new HttpUtil();
				String str = packet.getTo();
				String url = "http://localhost:8080/XmppHttpStub/stub";
				String result = httpUtil.send(url, new ByteArrayInputStream(str.getBytes()));
				sendPacket(result);
				System.out.println(id + "\tSample\trecv\tend");
			}

		}, new PacketFilter() {
			public boolean accept(Packet arg0) {
				return true;
			}
		});
	}
	
	public void sendPacket(final String str) {
		IQ iq = new IQ() {
			@Override
			public String getChildElementXML() {
				return str;
			}
		};
		String id = iq.getPacketID();
		iq.setType(IQ.Type.GET);
		iq.setTo("user01@localhost.localdomain/Smack");

		connection.sendPacket(iq);
	}
}