/*
 *  Copyright (C) 2006  Takashi Kasuya <kasuya@sfc.keio.ac.jp>
 *
 * This library is free software; you can redistribute it and/or
 *　modify it under the terms of the GNU Lesser General Public
 *　License as published by the Free Software Foundation; either
 *　version 2.1 of the License, or (at your option) any later version.
 *　This library is distributed in the hope that it will be useful,
 *　but WITHOUT ANY WARRANTY; without even the implied warranty of
 *　MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *　Lesser General Public License for more details.
 *
 *　You should have received a copy of the GNU Lesser General Public
 *　License along with this library; if not, write to the Free Software
 *　Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

package jp.ac.naka.ec.plugin.xmlrpc;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import jp.ac.naka.ec.EventSource;
import jp.ac.naka.ec.entity.Entity;
import jp.ac.naka.ec.entity.EntityContainer;
import jp.ac.naka.ec.entity.EntityEvent;
import jp.ac.naka.ec.entity.EntityImpl;
import jp.ac.naka.ec.entity.EntityListener;

import org.apache.xmlrpc.XmlRpc;
import org.apache.xmlrpc.XmlRpcClientLite;
import org.apache.xmlrpc.XmlRpcException;

/**
 * Blogへの投稿用プラグイン
 * 
 * @author Takashi Kasuya
 * 
 */
public class BlogPoster extends EventSource {
	String url = "http://ibaraki.iobb.net/mt/mt-xmlrpc.cgi";// 下記の情報を送るＵＲＬを記述します。

	String methodName = "metaWeblog.newPost";

	String blogid = "7";

	String username = "kasuya";// Login時のユーザーネームです。

	String password = "elecom30";// Login時のパスワードです。

	Integer publish = new Integer(1);// 記事を公開するかしないかを1,0で決定します。

	Vector params = new Vector();

	Entity source;

	List<EntityListener> targets = new ArrayList<EntityListener>();

	public BlogPoster() {
		XmlRpc.setEncoding("UTF-8");

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jp.ac.naka.ec.Plugin#init(jp.ac.naka.ec.entity.EntityContainer)
	 */
	public void init(EntityContainer source) throws Exception {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jp.ac.naka.ec.Plugin#init(jp.ac.naka.ec.entity.EntityContainer,
	 *      java.util.Properties)
	 */
	public void init(EntityContainer source, Properties prop) throws Exception {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jp.ac.naka.ec.EventSource#receiveMessage(jp.ac.naka.ec.entity.EntityEvent)
	 */
	@Override
	public void receiveMessage(EntityEvent evt) {
		if (evt.getTarget() != null && !evt.getTarget().equals(this)) {
			return;
		}
		String str = evt.getMessage();
		if (str == null)
			return;
		Mail mail = null;
		try {
			mail = getMail(str);
		} catch (Exception e) {
			return;
		}
		Hashtable<String, String> content = new Hashtable<String, String>();// structです。Title,Descriptionを入れます。
		content.put("title", mail.subject);
		content.put("description", mail.content);
		Vector<Serializable> params = new Vector<Serializable>();
		params.add(blogid);
		params.add(username);
		params.add(password);
		params.add(content);
		params.add(publish);

		try {
			XmlRpcClientLite client = new XmlRpcClientLite(url);
			// entry id
			Object result = client.execute(methodName, params);
			mail.entryId = Integer.parseInt(result.toString());
			if (source == null)
				source = new EntityImpl(getURI());
			for (EntityListener target : targets) {
				EntityEvent e = new EntityEvent(mail.toString(), target, source);
				dispatcher.dispatchEvent(e);
			}
		} catch (XmlRpcException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		params.remove(content);
	}

	/**
	 * @return the blogid
	 */
	public String getBlogId() {
		return blogid;
	}

	/**
	 * @param blogid
	 *            the blogid to set
	 */
	public void setBlogId(String blogid) {
		this.blogid = blogid;
	}

	/**
	 * @return the methodName
	 */
	public String getMethodName() {
		return methodName;
	}

	/**
	 * @param methodName
	 *            the methodName to set
	 */
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the publish
	 */
	public Integer getPublish() {
		return publish;
	}

	/**
	 * @param publish
	 *            the publish to set
	 */
	public void setPublish(Integer publish) {
		this.publish = publish;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url
	 *            the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @return the username
	 */
	public String getUserName() {
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUserName(String username) {
		this.username = username;
	}

	class Mail {
		String subject, content, path, latitude, longitude, date;

		int entryId;

		public String toString() {
			StringBuilder sb = new StringBuilder();
			sb.append("<mail>");
			sb.append(addTab("subject", subject));
			sb.append(addTab("content", content));
			sb.append(addTab("path", path));
			sb.append(addTab("latitude", latitude));
			sb.append(addTab("longitude", longitude));
			sb.append(addTab("date", date));
			sb.append(addTab("id", entryId + ""));
			sb.append("</mail>");
			return sb.toString();
		}

		public String addTab(String name, String content) {
			return "<" + name + ">" + content + "</" + name + ">";
		}
	}

	private Mail getMail(String message) {
		Mail mail = new Mail();
		String content, subject, path, lat, lon, date;
		int index = message.indexOf("<path>");
		int endIndex = message.indexOf("</path>");
		path = message.substring(index + "<path>".length(), endIndex);
		index = message.indexOf("<subject>");
		endIndex = message.indexOf("</subject>");
		subject = message.substring(index + "<subject>".length(), endIndex);
		index = message.indexOf("<content><![CDATA[");
		endIndex = message.indexOf("]]></content>");
		content = message.substring(index + "<content><![CDATA[".length(),
				endIndex);
		index = message.indexOf("<latitude>");
		endIndex = message.indexOf("</latitude>");
		lat = message.substring(index + "<latitude>".length(), endIndex);
		index = message.indexOf("<longitude>");
		endIndex = message.indexOf("</longitude>");
		lon = message.substring(index + "<longitude>".length(), endIndex);
		index = message.indexOf("<date>");
		endIndex = message.indexOf("</date>");
		date = message.substring(index + "<date>".length(), endIndex);
		mail.content = content;
		mail.subject = subject;
		mail.latitude = lat;
		mail.longitude = lon;
		mail.path = path;
		mail.date = date;
		return mail;
	}

	public static void main(String[] args) {
		BlogPoster blog = new BlogPoster();
		EntityEvent evt = new EntityEvent(
				"<mail><path>hoge</path><content>ほげ</content><latitude>100</latitude><longitude>100</longitude></mail>",
				blog, new EntityImpl());

		blog.receiveMessage(evt);
	}

	public void addTarget(EntityListener target) {
		targets.add(target);
	}
}
