/*******************************************************************************
 * Copyright (c) 1998, 2008 Oracle, Markus KARG(markus-karg@users.sourceforge.net). All rights reserved.
 * This program and the accompanying materials are made available under the 
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
 * which accompanies this distribution. 
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at 
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *     Markus Karg and Oracle - initial API and implementation from Oracle TopLink and TopLink Essentials
 *          05/16/2008-1.0 Markus Karg - 237843: CONCAT must be translated into || instead of + 
 *        
 ******************************************************************************/  
package org.eclipse.persistence.platform.database;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Hashtable;

import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.expressions.ExpressionOperator;
import org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition;
import org.eclipse.persistence.internal.helper.ClassConstants;
import org.eclipse.persistence.internal.helper.DatabaseTable;
import org.eclipse.persistence.queries.ValueReadQuery;

/**
 * Provides SQL Anywhere specific behaviour.
 * 
 * @author Markus KARG (markus-karg@users.sourceforge.net)
 */
public class SQLAnywherePlatform extends SybasePlatform {

    public SQLAnywherePlatform() {
        super();
    }
    
    @Override
// TODO: can't use these field types: none of them has sizes.
// That results is using defaults, that seem to be 9 for VARCHAR
// and neither FeatureTestModel nor AggregateTestModel would setup because of that.
// Untill this is fixed have to use the field types inherited from SybasePlatform.
/*    protected Hashtable buildFieldTypes() {
        Hashtable<Class, FieldTypeDefinition> fieldTypeMapping = new Hashtable<Class, FieldTypeDefinition>();
        fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("BIT", false));
        fieldTypeMapping.put(Integer.class, new FieldTypeDefinition("INTEGER", false));
        fieldTypeMapping.put(Long.class, new FieldTypeDefinition("BIGINT", false));
        fieldTypeMapping.put(Float.class, new FieldTypeDefinition("REAL", false));
        fieldTypeMapping.put(Double.class, new FieldTypeDefinition("DOUBLE", false));
        fieldTypeMapping.put(Short.class, new FieldTypeDefinition("SMALLINT", false));
        fieldTypeMapping.put(Byte.class, new FieldTypeDefinition("SMALLINT", false));
        fieldTypeMapping.put(BigInteger.class, new FieldTypeDefinition("BIGINT", false));
        fieldTypeMapping.put(BigDecimal.class, new FieldTypeDefinition("DOUBLE", false));
        fieldTypeMapping.put(Number.class, new FieldTypeDefinition("DOUBLE", false));
        fieldTypeMapping.put(String.class, new FieldTypeDefinition("VARCHAR"));
        fieldTypeMapping.put(Character.class, new FieldTypeDefinition("CHAR"));
        fieldTypeMapping.put(Byte[].class, new FieldTypeDefinition("LONG BINARY", false));
        fieldTypeMapping.put(Character[].class, new FieldTypeDefinition("LONG VARCHAR", false));
        fieldTypeMapping.put(byte[].class, new FieldTypeDefinition("LONG BINARY", false));
        fieldTypeMapping.put(char[].class, new FieldTypeDefinition("LONG VARCHAR", false));
        fieldTypeMapping.put(Blob.class, new FieldTypeDefinition("LONG BINARY", false));
        fieldTypeMapping.put(Clob.class, new FieldTypeDefinition("LONG VARCHAR", false));
        fieldTypeMapping.put(Date.class, new FieldTypeDefinition("DATE", false));
        fieldTypeMapping.put(Time.class, new FieldTypeDefinition("TIME", false));
        fieldTypeMapping.put(Timestamp.class, new FieldTypeDefinition("TIMESTAMP", false));
        return fieldTypeMapping;
    }*/

    /**
     * INTERNAL:
     * Build the identity query for native sequencing.
     */
    public ValueReadQuery buildSelectQueryForIdentity() {
        ValueReadQuery selectQuery = new ValueReadQuery();
        StringWriter writer = new StringWriter();
        writer.write("SELECT @@IDENTITY");
        selectQuery.setSQLString(writer.toString());
        return selectQuery;
    }

    public static ExpressionOperator createCurrentDateOperator() {
        return ExpressionOperator.simpleFunctionNoParentheses(ExpressionOperator.CurrentDate, "CURRENT DATE");
    }

    public static ExpressionOperator createCurrentTimeOperator() {
        return ExpressionOperator.simpleFunctionNoParentheses(ExpressionOperator.CurrentTime, "CURRENT TIME");
    }

    public static ExpressionOperator createLocate2Operator() {
        return ExpressionOperator.simpleThreeArgumentFunction(ExpressionOperator.Locate2, "LOCATE");
    }

    public static ExpressionOperator createConcatOperator() {
        return ExpressionOperator.simpleLogicalNoParens(ExpressionOperator.Concat, "||");
    }

    public static ExpressionOperator createLocateOperator() {
        return ExpressionOperator.simpleTwoArgumentFunction(ExpressionOperator.Locate, "LOCATE");
    }

    @Override
    protected String getCreateTempTableSqlPrefix() {
        return "DECLARE TEMPORARY TABLE ";
    }

    @Override
    public int getJDBCType(Class javaType) {
        return javaType == ClassConstants.BLOB ? Types.LONGVARBINARY :  javaType == ClassConstants.CLOB ? Types.LONGVARCHAR : super.getJDBCType(javaType);
    }

    @Override
    public int getMaxFieldNameSize() {
        return 128;
    }

    @Override
    public DatabaseTable getTempTableForTable(DatabaseTable table) {
        return new DatabaseTable("$" + table.getName(), table.getTableQualifier());
    }

    @Override
    protected void initializePlatformOperators() {
        super.initializePlatformOperators();
        this.addOperator(createConcatOperator());
        this.addOperator(createLocateOperator());
        this.addOperator(createLocate2Operator());
//        this.addOperator(createCurrentDateOperator());
//        this.addOperator(createCurrentTimeOperator());
        this.addOperator(ExpressionOperator.charLength());
        this.addOperator(ExpressionOperator.mod());
    }

    public boolean isSQLAnywhere() {
        return true;
    }

    public boolean isSybase() {
        return false;
    }

    @Override
    public void printFieldIdentityClause(Writer writer) throws ValidationException {
        try {
            writer.write(" DEFAULT AUTOINCREMENT");
        } catch (IOException ioException) {
            throw ValidationException.fileError(ioException);
        }
    }

    @Override
    public void printFieldNullClause(Writer writer) throws ValidationException {
        try {
            writer.write(" NULL");
        } catch (IOException ioException) {
            throw ValidationException.fileError(ioException);
        }
    }


    @Override
    public boolean supportsLocalTempTables() {
        return true;
    }

    @Override
    public boolean supportsIdentity() {
        return true;
    }

    @Override
    public boolean supportsStoredFunctions() {
        return true;
    }

    /**
     * INTERNAL
     * Allows platform to choose whether to bind literals in DatabaseCalls or not.
     */
    public boolean shouldBindLiterals() {
        return false;
    }
}
