package hiro.yoshioka.sql;

import hiro.yoshioka.ast.sql.oracle.WolfSQLParserConstants;
import hiro.yoshioka.sql.resource.DBColumn;
import hiro.yoshioka.sql.resource.DBTable;
import hiro.yoshioka.util.SQLDataType;
import hiro.yoshioka.util.SQLUtil;

import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SybaseSQL extends GeneralSQL {
	protected SybaseSQL(Driver driver) {
		super(driver);
	}

	public boolean close() throws SQLException {
		boolean status = true;
		try {
			if (_con != null) {
				if (!_con.isClosed()) {
					_con.close();
					fLogger.warn("Closed user connection");
				}
			}
			if (_extra_con != null) {
				if (!_extra_con.isClosed()) {
					_extra_con.close();
					fLogger.warn("Closed background connection");
				}
			}
		} finally {
			_con = null;
			_extra_con = null;
			for (int i = 0; i < fConnectionListenerList.size(); i++) {
				fConnectionListenerList.get(i).disconnected();
			}
		}
		return status;
	}

	protected void setTableColumns(String schema, DBTable table)
			throws SQLException {
		List<String> pkey = getTablePrimaryKeys(null, schema, table.getName());

		ResultSet rs = null;
		Statement st = null;
		try {
			rs = _con.getMetaData().getColumns(null, schema, table.getName(),
					"%");

			while (rs.next()) {
				DBColumn col = new DBColumn(table);
				col.setName(rs.getString(4));
				col.setDataType(SQLDataType.parse(rs.getShort(5)));
				col.setSize(rs.getShort(7));
				col.setDecimalDigits(rs.getInt(9));
				col.setNullable((short) rs.getInt(11));
				col.setPKey(pkey);
				col.setDataTypeString(rs.getString(6));
				col.setMaxColumnNameLength(SQLUtil
						.getMaxColumnNameBytes(_extra_con));

				table.putResource(col.getUName(), col);
			}
		} catch (Exception e) {
			fLogger.trace(e);
			return;
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
		}
	}

	protected String getSupportToken() {
		StringBuffer buf = new StringBuffer();
		Pattern p = Pattern.compile("\"(\\w+)\"");
		String[] str = WolfSQLParserConstants.tokenImage;
		for (int i = 0; i < str.length; i++) {
			Matcher m = p.matcher(str[i]);
			if (m.matches()) {
				buf.append(m.group(1)).append(",");
			}
		}
		if (buf.length() > 0) {
			buf.setLength(buf.length() - 1);
		}
		return buf.toString();
	}

	public static String getSuggestURL() {
		return "jdbc:sqlserver://127.0.0.1:1433;databaseName=NAME;selectMethod=cursor";
	}

	public static String getLimitString() {
		return "WHERE ROWNUM < 30";
	}

}