package org.postgresforest.vm.core;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

import org.postgresforest.core.ParameterList;
import org.postgresforest.core.Query;
import org.postgresforest.vm.Parser;
import org.postgresforest.vm.ReWriter;

public class SimpleQuery implements Query {

	
	//構文解析
	protected Parser m_parser;

	protected SQLException m_parserErr;

	/** クエリタイプ */
	protected int m_queryType = ReWriter.TYPE_NONE;

	/** 実行クエリー数  */
    protected int m_queryNum = 0;
	
    /** Timeout (in seconds) for a query  */
    protected int m_timeout = 0;

    protected HashMap m_preparedQueryMap;
	
	public SimpleQuery(Parser parser) {
		super();
		// TODO 自動生成されたコンストラクター・スタブ
		m_parser = parser;
		
		m_preparedQueryMap = new HashMap(); 
	}

	
	
	public ParameterList createParameterList() {
        return new SimpleParameterList(m_parser.getParamNum()-1);
	}


	public void close() {
		// TODO 自動生成されたメソッド・スタブ

	}




	public String toString(ParameterList parameters) {
    	return m_parser.toString(parameters);
    }

    public String toString() {
        return toString(null);
    }
	
	
	
	
	
	
	
	public Parser getParser() throws SQLException {
		if(m_parserErr != null){
			throw m_parserErr;
		}
		
		return m_parser;
	}

	public void setParser(Parser parser) {
		m_parser = parser;
	}



	public int getTimeout() {
		return m_timeout;
	}



	public void setTimeout(int timeout) {
		m_timeout = timeout;
	}



	public int getQueryNum() {
		return m_queryNum;
	}



	public void setQueryNum(int queryNum) {
		m_queryNum = queryNum;
	}



	public int getQueryType() {
		return m_queryType;
	}



	public void setQueryType(int queyType) {
		m_queryType = queyType;
	}



	public Query getPreparedQuery(Connection con, String rewriteSQL ) {
		
		synchronized (m_preparedQueryMap) {
		
			HashMap hashMap = (HashMap)m_preparedQueryMap.get(con);
			if( hashMap == null){
				return null;
				
			}else{
				return (Query)hashMap.get(rewriteSQL);
			}
		}
		
	}
	
    public void putPreparedQuery(Connection con, String rewriteSQL, Query query) {

		synchronized (m_preparedQueryMap) {
			HashMap hashMap = (HashMap)m_preparedQueryMap.get(con);
			if( hashMap == null){
				hashMap = new HashMap();
				m_preparedQueryMap.put(con,hashMap);
			}
			hashMap.put(rewriteSQL,query);
		}		
	}



	public void setParserErr(SQLException parserErr) {
		m_parserErr = parserErr;
	}



	public SQLException getParserErr() {
		return m_parserErr;
	}

	
	
	
}
