/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.eql.parser.generic;

import com.queplix.core.error.GenericSystemException;
import com.queplix.core.jxb.entity.Efield;
import com.queplix.core.jxb.entity.Entity;
import com.queplix.core.modules.eql.EQLDateObject;
import com.queplix.core.modules.eql.EQLERes;
import com.queplix.core.modules.eql.EQLNullObject;
import com.queplix.core.modules.eql.EQLNumberObject;
import com.queplix.core.modules.eql.EQLObject;
import com.queplix.core.modules.eql.EQLResCell;
import com.queplix.core.modules.eql.EQLResRecord;
import com.queplix.core.modules.eql.EQLStringObject;
import com.queplix.core.modules.eql.EQLTimeObject;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.eql.parser.SQLUpdateBuilder;
import com.queplix.core.utils.StringHelper;

/**
 * <p>Update SQL builder generic implementation</p>
 *
 * @author Baranov Andrey [ALB]
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:31 $
 */

public class SQLUpdateBuilderGenericImpl
        extends SQLUpdateBuilder {

// ------------ PROTECTED OVERRIDED METHODS ----------------

    /*
     * (No javadoc)
     * @see SQLBuilder#getInsertSql
     */

    protected String getInsertSql(EQLERes res, EQLResRecord resRecord)
            throws EQLException {

        Entity entity = res.getEntity();

        StringBuffer sql1 = new StringBuffer();
        sql1.append("\nINSERT INTO\n ");
        sql1.append(entity.getDbobject());
        sql1.append("\n(");

        StringBuffer sql2 = new StringBuffer();
        sql2.append("\nVALUES\n(");

        // add fields and values
        int fieldsAdded = 0;
        int size = resRecord.size();
        for(int i = 0; i < size; i++) {
            EQLResCell resCell = resRecord.getResCell(i);
            Efield field = resCell.getReqField().getField();

            // filed is updateable?
            if(field.getUpdatable().booleanValue()) {

                // EQL object
                EQLObject eqlObj = resCell.getEQLObject();

                if(fieldsAdded > 0) {
                    sql1.append(",");
                    sql2.append(",");
                }

                sql1.append(field.getName().toUpperCase());
                sql2.append(_getSQLValue(eqlObj));

                fieldsAdded++;
            }
        }

        sql1.append(")");
        sql2.append(")");

        return (fieldsAdded > 0) ? (sql1.toString() + sql2.toString()):null;
    }

    /*
     * (No javadoc)
     * @see SQLBuilder#getUpdateSql
     */
    protected String getUpdateSql(EQLERes res, EQLResRecord resRecord)
            throws EQLException {

        Entity entity = res.getEntity();
        int size = resRecord.size();

        // add fields and values
        int fieldsAdded = 0;
        StringBuffer sql1 = new StringBuffer();
        sql1.append("\nUPDATE ");
        sql1.append(entity.getDbobject());
        sql1.append(" SET\n");

        for(int i = 0; i < size; i++) {
            EQLResCell resCell = resRecord.getResCell(i);
            Efield field = resCell.getReqField().getField();

            if(resCell.isValueChanged() && field.getUpdatable()
                    .booleanValue()) {

                // get EQL object
                EQLObject eqlObj = resCell.getEQLObject();

                // filed is updateable
                if(fieldsAdded > 0) {
                    sql1.append(",");
                }

                sql1.append(field.getName().toUpperCase());
                sql1.append(" = ");
                sql1.append(_getSQLValue(eqlObj));

                fieldsAdded++;
            }
        }

        // add constraint
        int pkeysAdded = 0;
        StringBuffer sql2 = new StringBuffer();
        sql2.append("\nWHERE\n");

        for(int i = 0; i < size; i++) {
            EQLResCell resCell = resRecord.getResCell(i);
            Efield field = resCell.getReqField().getField();

            if(field.getPkey().booleanValue()) {
                // field is pkey!
                EQLObject pkeyEqlObj = resCell.getOldEQLObject();

                if(pkeysAdded > 0) {
                    sql2.append(" AND ");
                }

                sql2.append(field.getName().toUpperCase());
                sql2.append(" = ");
                sql2.append(_getSQLValue(pkeyEqlObj));

                pkeysAdded++;
            }
        }

        if(pkeysAdded == 0) {
            throw new GenericSystemException(
                    "Can't find pkey in entity '" + entity.getName() + "'");
        }

        return (fieldsAdded > 0) ? (sql1.toString() + sql2.toString()):null;
    }

    /*
     * (No javadoc)
     * @see SQLBuilder#getDeleteSql
     */
    protected String getDeleteSql(EQLERes res, EQLResRecord resRecord)
            throws EQLException {

        Entity entity = res.getEntity();

        StringBuffer sql = new StringBuffer();
        sql.append("\nDELETE FROM ");
        sql.append(entity.getDbobject());
        sql.append(" WHERE\n");

        // add fields and values
        int pkeysAdded = 0;
        int size = resRecord.size();
        for(int i = 0; i < size; i++) {
            EQLResCell resCell = resRecord.getResCell(i);
            Efield field = resCell.getReqField().getField();

            // filed is pkey?
            if(!field.getPkey().booleanValue()) {
                continue;
            }

            // EQL object
            EQLObject eqlObj = resCell.getEQLObject();

            if(pkeysAdded > 0) {
                sql.append(" AND ");
            }

            sql.append(field.getName().toUpperCase());
            sql.append(" = ");
            sql.append(_getSQLValue(eqlObj));

            pkeysAdded++;
        }

        if(pkeysAdded == 0) {
            throw new GenericSystemException(
                    "Can't find pkey in entity '" + entity.getName() + "'");
        }

        return sql.toString();
    }

    //
    // Values
    //

    protected String getSQLValue(EQLStringObject o)
            throws EQLException {
        return StringHelper.java2sql(o.getValue());
    }

    protected String getSQLValue(EQLNumberObject o)
            throws EQLException {
        return o.getValue().toString();
    }

    protected String getSQLValue(EQLDateObject o)
            throws EQLException {
        return sqlWrapper.getTimestampParser().sqlDateFunction(o.getValue());
    }

    protected String getSQLValue(EQLTimeObject o)
            throws EQLException {
        return sqlWrapper.getTimeParser().sqlTimeFunction(o.getValue());
    }

    protected String getSQLValue(EQLNullObject o)
            throws EQLException {
        return "NULL";
    }
}
