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

import hiro.yoshioka.ast.sql.AbsSimpleNode;
import hiro.yoshioka.ast.sql.IToken;
import hiro.yoshioka.ast.sql.oracle.ASTSelectColumns;
import hiro.yoshioka.ast.sql.oracle.ASTSelectColumnsElement;
import hiro.yoshioka.ast.sql.oracle.ASTSelectThird;
import hiro.yoshioka.ast.sql.oracle.SimpleNode;
import hiro.yoshioka.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

public class SimpleSelectionVisitor extends DefaultSQLNodeVisitor {
	private List<String> selectFieldList = new ArrayList<String>();
	private String sql_statement;

	public SimpleSelectionVisitor(String sql) {
		this.sql_statement = sql;
	}

	public List<String> getSelectFieldList() {
		return selectFieldList;
	}

	String getLine(AbsSimpleNode node) {
		String stext = sql_statement;
		String line = new BackWord(stext).backWord(node.getFirstToken(),
				node.getLastToken());
		return line;
	}

	public class BackWord {
		String fTargetText;

		public BackWord(String targetText) {
			fTargetText = targetText;
		}

		public String backWord(IToken begin, IToken end) {
			String lsp = StringUtil.getThisLineSeparator(fTargetText);
			String[] lineData = fTargetText.split(lsp, -1);
			StringBuffer ret = new StringBuffer();
			for (int i = begin.getBeginLine() - 1; i <= end.getEndLine() - 1; i++) {
				if (i == begin.getBeginLine() - 1) {
					if (i == end.getEndLine() - 1) {
						ret.append(lineData[i].substring(
								begin.getBeginColumn() - 1, end.getEndColumn()));
					} else {
						ret.append(lineData[i].substring(begin.getBeginColumn() - 1));
					}
				} else if (i > begin.getBeginLine() - 1) {
					if (i == end.getEndLine() - 1) {
						ret.append(lineData[i].substring(0, end.getEndColumn()));
					} else {
						ret.append(lineData[i]);
					}
				} else {

					System.out.println("ELSE[" + lineData[i]);
				}
			}
			return ret.toString();
		}

	}

	public Object doJob(SimpleNode node, Object data) {
		SimpleNode n;
		for (int ord = 0; ord < node.jjtGetNumChildren(); ord++) {
			n = (SimpleNode) node.jjtGetChild(ord);
			n.jjtAccept(this, data);
		}
		return data;
	}

	public Object visit(ASTSelectThird node, Object data) {

		// appendln("SELECT ");

		AbsSimpleNode[] nodes = node.getChildren();
		for (int i = 0; i < nodes.length; i++) {
			((SimpleNode) nodes[i]).jjtAccept(this, data);
		}
		return null;
	}

	public Object visit(ASTSelectColumns node, Object data) {
		return super.visit(node, data);
	}

	public Object visit(ASTSelectColumnsElement node, Object data) {
		selectFieldList.add(node.getLastToken().getImage());
		return null;
	}

}
