package hiro.yoshioka.sql.notes.ddl;

import hiro.yoshioka.sdh.ResultSetDataHolder;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Database implements Serializable {
	private static final long serialVersionUID = -6342467648865199103L;
	private List<Form> formList = new ArrayList<Form>();
	private Map<String, Field> sharedFieldMap;

	public Database(Node database, Set<String> parseTargetFormSets) {
		NodeList list = database.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			Node child = list.item(i);

			if ("sharedfield".equals(child.getNodeName())) {
				if (sharedFieldMap == null) {
					sharedFieldMap = new LinkedHashMap<String, Field>();
				}
				NamedNodeMap names = database.getAttributes();
				String name = Form.getAttrValueString(names, "name");
				NodeList list0 = child.getChildNodes();
				for (int j = 0; j < list0.getLength(); j++) {
					if ("field".equals(list.item(j).getNodeName())) {
						sharedFieldMap.put(name, new Field(list.item(j)));
					}
				}
			} else if ("form".equals(child.getNodeName())) {
				parseForm(child, parseTargetFormSets);
			} else if ("subform".equals(child.getNodeName())) {

			} else if ("view".equals(child.getNodeName())) {

			} else {
				System.err.println("??parseDatabase#child="
						+ child.getNodeName());
			}
		}
	}

	public Field getSharedField(String name) {
		return sharedFieldMap.get(name);
	}

	private void parseForm(Node formNode, Set<String> parseTargetFormSets) {
		Form form = new Form(this, formNode);
		if (parseTargetFormSets != null) {
			if (!parseTargetFormSets.contains(form.getName())
					&& !parseTargetFormSets.contains(form.getAlias())) {
				form = null;
				return;
			}
		}
		form.parseBody(formNode);
		formList.add(form);
	}

	public String toHtmlString(ResultSetDataHolder rdh, int row, File imgDir) {
		StringBuilder buf = new StringBuilder();
		for (Form form : formList) {
			buf.append(form.toHtmlString(rdh, row, imgDir));
			buf.append(String
					.format("-----------------------------------------------<br>%n"));
		}
		return buf.toString();
	}

	public Form getFromAt(int idx) {
		return formList.get(idx);
	}

	public Form getFrom(String formName) {
		for (Form f : formList) {
			if (formName.equals(f.getName()) || formName.equals(f.getAlias())) {
				return f;
			}
		}
		return null;
	}
}
