package org.bench4q.recorder.httpcapture.generator;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.bench4q.recorder.httpcapture.Config;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlDocumentParser {
	private Document document;
	private static Logger logger = Logger.getLogger(HtmlDocumentParser.class);
	private static String recordFlagHtml = null;

	private static void initRecordFlagHtml() {
		String pathSep = System.getProperty("file.separator");
		String recordFlagFilePath = "org" + pathSep + "bench4q" + pathSep
				+ "master" + pathSep + "config" + pathSep + "httpCaptureConfig"
				+ pathSep + Config.getConfig().getProperty("record.flag.file");

		InputStream is = HtmlDocumentParser.class.getClassLoader()
				.getResourceAsStream(recordFlagFilePath);
		if (is == null)
			return;
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		int n;
		try {
			while ((n = is.read(b)) != -1) {
				out.append(new String(b, 0, n));
			}
			recordFlagHtml = out.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static String getRecordFlagHtml() {
		if (recordFlagHtml == null) {
			initRecordFlagHtml();
		}
		return recordFlagHtml;
	}

	private Document getDocument() {
		return document;
	}

	private void setDocument(Document document) {
		this.document = document;
	}

	public HtmlDocumentParser(String htmlContent, String baseUrl) {
		this.setDocument(Jsoup.parse(htmlContent, baseUrl));
	}

	public String toString() {
		return this.getDocument().toString();
	}

	public void beginParse() {

	}

	/**
	 * 
	 */
	public void appendRecordFlag() {
		String recordFlagHtml = getRecordFlagHtml();
		if (recordFlagHtml != null)
			this.getDocument().body().append(recordFlagHtml);
	}

	public List<ChildrenUrl> buildParentChildrenRelationship(int parentBatchId) {
		List<ChildrenUrl> result = new ArrayList<ChildrenUrl>();
		if (parentBatchId == -1) {
			return result;
		}

		Elements allChildrenLinks = new Elements();
		allChildrenLinks.addAll(this.getDocument().select("[src]"));
		allChildrenLinks.addAll(this.getDocument().select("link[href]"));

		logger.info("Following url shuold in children urls: \n");
		for (Element element : allChildrenLinks) {
			String childAbsoluteUrl = element.absUrl("src");
			if (childAbsoluteUrl.isEmpty()) {
				childAbsoluteUrl = element.absUrl("href");
			}
			logger.info(childAbsoluteUrl);
			result.add(ChildrenUrl.createChilldUrl(childAbsoluteUrl,
					parentBatchId));
		}
		return result;
	}
}
