package hiro.yoshioka.ast.sql.oracle.util;

import hiro.yoshioka.ast.sql.IDML;
import hiro.yoshioka.ast.sql.ITableAssistDL;
import hiro.yoshioka.ast.sql.RowColumn;
import hiro.yoshioka.ast.sql.oracle.ASTDefaultDDL;
import hiro.yoshioka.ast.sql.oracle.SimpleNode;
import hiro.yoshioka.ast.sql.util.ASTEditorTableListHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class TableListFindSQLNodeVisitor extends DefaultSQLNodeVisitor {
	private Set<ASTEditorTableListHolder> tableSet;
	public boolean forceClipDML;

	public List<ASTEditorTableListHolder> getTableListHolder() {
		if (tableSet == null || tableSet.size() == 0) {
			return Collections.EMPTY_LIST;
		}
		return new ArrayList<ASTEditorTableListHolder>(tableSet);
	}

	private void add(ASTEditorTableListHolder target) {
		if (tableSet == null) {
			tableSet = new LinkedHashSet<ASTEditorTableListHolder>();
		}
		tableSet.add(target);
	}

	public Object doJob(SimpleNode node, Object data) {
		if (node instanceof ASTDefaultDDL && node.contain((RowColumn) data)) {
			if (log.isInfoEnabled()) {
				log.info(node + " instanceof ASTDefaultDDL" + node.getClass()
						+ " TH[" + ((ASTDefaultDDL) node).fTableHolder + "] ");
			}
			v.add(node);
			add(((ASTDefaultDDL) node).fTableHolder);
		} else if (node instanceof IDML
				&& (node.contain((RowColumn) data) || forceClipDML)) {
			if (log.isInfoEnabled()) {
				log.info(node + " instanceof IDML" + node.getClass() + " TH["
						+ ((IDML) node).getEditorTableListHolder() + "]");
			}
			v.add(node);
			add(((IDML) node).getEditorTableListHolder());
		} else if (node instanceof ITableAssistDL
				&& (node.contain((RowColumn) data))) {
			if (log.isInfoEnabled()) {
				log.info(node + " instanceof ITableAssistDL" + node.getClass()
						+ " TH["
						+ ((ITableAssistDL) node).getEditorTableListHolder()
						+ "]");
			}
			v.add(node);
			add(((ITableAssistDL) node).getEditorTableListHolder());
		}
		if (!node.contain((RowColumn) data)) {
			if (node instanceof ASTDefaultDDL || node instanceof IDML) {
				if (log.isInfoEnabled()) {
					log.info("これあうと" + node);
				}
			}
		}
		SimpleNode n;
		for (int ord = 0; ord < node.jjtGetNumChildren(); ord++) {
			n = (SimpleNode) node.jjtGetChild(ord);

			n.jjtAccept(this, data);
		}
		return v;
	}
}