package org.jerrymouse.cc.site.web.spider;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.io.IOUtils;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.Source;

public class FlvcdSpider implements FlvSplider {
	private String[] supportHosts = { "tudou.com" };

	String orgUrl;
	String url;
	String name;

	public FlvcdSpider(String orgUrl) {
		this.orgUrl = orgUrl;
	}

	@SuppressWarnings("unchecked")
	private void splide() {
		try {
			URL url = new URL("http://www.flvcd.com/parse.php?kw="
					+ URLEncoder.encode(orgUrl, "utf-8"));
			String responseBody = IOUtils.toString(url.openStream());
			Source source = new Source(responseBody);
			List<Element> elements = source.findAllElements(HTMLElementName.B);
			name = elements.get(0).getContent().toString();
			elements = source.findAllElements("onclick",
					"_alert();return false;", false);
			this.url = elements.get(0).getAttributeValue("href");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isSupport() {
		URL url;
		try {
			url = new URL(orgUrl);
			String h = url.getHost();
			for (String sh : supportHosts) {
				if (h.contains(sh)) {
					return true;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public String getName() {
		if (name == null)
			splide();
		return name;
	}

	public String getUrl() {
		if (url == null)
			splide();
		return url;
	}

}
