package misc;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.cyberneko.html.parsers.DOMParser;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class NekoHtmlTest2 {

	String path = "src/test/resources/selenium_test.html";

	String expected = "open,/ig?hl=ja,\n" +
			"type,q,cfneo,\n" +
			"click,btnG,\n" +
			"clickAndWait,btnG,\n" +
			"clickAndWait,link=cfneoとは - はてなキーワード,\n";
	String actual = "";
	@Test
	public void test() {
		try {
			DOMParser parser = new DOMParser();
			parser.parse(new InputSource(
					new InputStreamReader(new FileInputStream(path), "UTF-8")));
			Document doc = parser.getDocument();
			Element root = doc.getDocumentElement();
			this.proc1(root);
			assertEquals(expected, actual);
		} catch (Exception e) {
			e.printStackTrace();
			fail();
		}
	}

	public void proc1(Element root) {
		if (root.getTagName().equals("TBODY")) {
			this.proc2(root, 0);
		} else {
			NodeList items = root.getChildNodes();
			for (int i = 0; i < items.getLength(); i++) {
				if (items.item(i).getNodeType() == Node.ELEMENT_NODE) {
					this.proc1((Element) items.item(i));
				}
			}
		}
	}

	public void proc2(Element root, int indent) {
		if ("TR".equals(root.getTagName())) {
			this.proc3((Element) root);
		} else {
			NodeList items = root.getChildNodes();
			for (int i = 0; i < items.getLength(); i++) {
				Node item = items.item(i);
				if (item.getNodeType() == Node.ELEMENT_NODE) {
					this.proc2((Element) item, indent + 1);
				}
			}
		}
	}

	public void proc3(Element root) {
		NodeList items = root.getChildNodes();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < items.getLength(); i++) {
			Node item = items.item(i);
			if (item.getNodeType() == Node.ELEMENT_NODE) {
				Element e2 = (Element) item;
				if ("TD".equals(e2.getTagName()) && e2.hasChildNodes()) {
					String s = e2.getFirstChild().getNodeValue().trim();
					if (s != null) {
						sb.append(s);
						sb.append(",");
					}
				}
			}
		}
		// CSVで出力
		System.out.println(sb);
		actual = actual + sb.toString() + "\n";
	}

}
