/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *
 */
package org.teiid.translator.jdbc;

import org.teiid.language.Expression;
import org.teiid.language.Function;
import org.teiid.language.SQLConstants.Tokens;
import org.teiid.translator.SourceSystemFunctions;

import java.util.ArrayList;
import java.util.List;


/**
 * Convert the DATE_TRUNC function into an equivalent function that can be pushed down to multiple DBs.
 * Format: SELECT DATE_TRUNC('YEAR', '2004-03-03 12:34:56.123456789')
 */
public class BaseDateTruncFunctionModifier extends FunctionModifier {

    final String castTarget;

    public BaseDateTruncFunctionModifier() {
        this(null);
    }

    public BaseDateTruncFunctionModifier(String castTarget) {
        this.castTarget = castTarget;
    }

    @Override
    public List<?> translate(Function function) {
        List<Expression> args = function.getParameters();

        List<Object> objs = new ArrayList<>();

        objs.add(getFunName());
        objs.add(Tokens.LPAREN);
        objs.add(getFirstParam(args));
        objs.add(Tokens.COMMA);
        objs.add(getSecondParam(args));
        objs.add(Tokens.RPAREN);

        if (castTarget != null) {
            objs.add(0, "CAST("); //$NON-NLS-1$
            objs.add(" AS "); //$NON-NLS-1$
            objs.add(castTarget);
            objs.add(")"); //$NON-NLS-1$
        }

         return objs;
    }

    protected String getFunName() {
        return SourceSystemFunctions.DATE_TRUNC;
    }

    protected Object getFirstParam(List<Expression> args) {
        return args.get(0);
    }

    protected Object getSecondParam(List<Expression> args) {
        return args.get(1);
    }
}

