package com.palacesun.engine.common;

import java.util.HashMap;
import java.util.Map;

public class CallableStatementInformation extends PreparedStatementInformation {
   private final Map<String, Value> namedParameterValues = new HashMap();

   public CallableStatementInformation(ConnectionInformation connectionInformation, String query) {
      super(connectionInformation, query);
   }

   public String getSqlWithValues() {
      if (this.namedParameterValues.size() == 0) {
         return super.getSqlWithValues();
      } else {
         StringBuilder result = new StringBuilder();
         String statementQuery = this.getStatementQuery();
         result.append(statementQuery);
         result.append(" ");
         StringBuilder parameters = new StringBuilder();

         for(Map.Entry<Integer, Value> entry : this.getParameterValues().entrySet()) {
            this.appendParameter(parameters, ((Integer)entry.getKey()).toString(), (Value)entry.getValue());
         }

         for(Map.Entry<String, Value> entry : this.namedParameterValues.entrySet()) {
            this.appendParameter(parameters, (String)entry.getKey(), (Value)entry.getValue());
         }

         result.append(parameters);
         return result.toString();
      }
   }

   private void appendParameter(StringBuilder parameters, String name, Value value) {
      if (parameters.length() > 0) {
         parameters.append(", ");
      }

      parameters.append(name);
      parameters.append(":");
      parameters.append(value != null ? value.toString() : (new Value()).toString());
   }

   public void setParameterValue(String name, Object value) {
      this.namedParameterValues.put(name, new Value(value));
   }
}
