package com.sap.dbmtk.demo;

import java.sql.Types;

import com.sap.dbmtk.demo.ui.ResultSetTableModel;
import com.sap.dbmtk.demo.utils.StringUtil;

public class SqlStatementParam
{
	private int     _sqlType   = Types.OTHER;
	private Object  _val       = null;
	private String  _paramName = null;
	private boolean _isOutput  = false;

	public boolean isOutput()     { return _isOutput; }
	public boolean isInput()      { return ! _isOutput; }
	public Object  getValue()     { return _val; }
	public int     getSqlType()   { return _sqlType; }
	public String  getParamName() { return _paramName; }
	
	 /**
	  * The SQL TYPE for an Oracle CURSOR in a Oracle Stored Procedure.
	  * This duplicates the OracleTypes.CURSOR, but with this constant 
	  * we do not need to import com.oracle.* jars into this project.
	  * However this class is still 100% dependent on Oracle at runtime 
	  * and cannot be unit tested without Oracle.
	  */
	private static int ORACLE_CURSOR_TYPE = -10;

	private SqlStatementParam()
	{
	}

	public static SqlStatementParam createInParam(String paramName, int sqlType, Object val)
	{
		SqlStatementParam p = new SqlStatementParam();

		p._paramName = paramName;
		p._isOutput  = false;
		p._sqlType   = sqlType; 
		p._val       = val;

		return p;
	}

	public static SqlStatementParam createOutParam(String paramName, int sqlType)
	{
		SqlStatementParam p = new SqlStatementParam();

		p._paramName = paramName;
		p._isOutput  = true;
		p._sqlType   = sqlType; 
		p._val       = null;

		return p;
	}

	public static SqlStatementParam createOracleResultSetParam(String paramName)
	{
		SqlStatementParam p = new SqlStatementParam();

		p._paramName = paramName;
		p._isOutput  = true;
		p._sqlType   = ORACLE_CURSOR_TYPE; 
		p._val       = null;

		return p;
	}

	public void setOutputParamValue(Object val)
	{
		_val = val;
	}

	public boolean isOracleRsParam()
	{
		return _sqlType == ORACLE_CURSOR_TYPE;
	}
	
	@Override
	public String toString()
	{
		String str = "Param: name=" + StringUtil.left(_paramName, 15) + (_isOutput ? " OUT, " : " IN,  ");
		
		if (_sqlType == ORACLE_CURSOR_TYPE)
		{
			str += "sqlType=ORACLE::REF_CURSOR";
			str += ", value=" + (_val == null ? "NULL" : "-HAS-RESULT-SET-") + ".";
		}
		else
		{
			str += "sqlType="+ResultSetTableModel.getColumnJavaSqlTypeName(_sqlType);
			str += ", value=" + (_val == null ? "NULL" : "'"+_val+"'") + ".";
		}

		return str;
	}
}
