/*
 * 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.
 */

package org.teiid.translator.jdbc.sqlserver;

import org.teiid.language.AggregateFunction;
import org.teiid.language.Expression;
import org.teiid.language.Function;
import org.teiid.language.Literal;
import org.teiid.translator.jdbc.FunctionModifier;
import org.teiid.translator.jdbc.SQLConversionVisitor;

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

/**
 * Convert the STRING_AGG function into an equivalent function that can be pushed down to MSSQL.
 *
 * @author Roman Pedchenko
 * @date 2021.10.06
 */
public class StringAggFunctionModifier extends FunctionModifier {
    public static final String UNSUPPORTED_EXPR = "MSSQL does not support expressions as delimiter in STRING_AGG function: %s. Please, resubmit your query specifying a Literal value";
    public static final String UNSUPPORTED_DISTINCT = "MSSQL does not support DISTINCT option in STRING_AGG function. Please, resubmit your query removing the distinct option.";

    public List<?> translate(Function function) {
        if (!(function instanceof AggregateFunction))
            return null;
        AggregateFunction aggregate = (AggregateFunction) function;
        List<Expression> args = aggregate.getParameters();
        Expression expr = args.get(0);
        Expression delimiter = args.get(1);
        if (aggregate.isDistinct())
            throw new RuntimeException(UNSUPPORTED_DISTINCT);
        if (!(delimiter instanceof Literal))
            throw new RuntimeException(String.format(UNSUPPORTED_EXPR, delimiter));
        List<Object> result = new ArrayList<>();
        result.add("string_agg(");
        result.add(expr);
        result.add(", ");
        result.add(new SQLConversionVisitor.NoPrefixLiteral((Literal) delimiter));
        result.add(")");
        if (aggregate.getOrderBy() != null) {
            result.add(" within group (");
            result.add(aggregate.getOrderBy());
            result.add(")");
        }
        return result;
    }
}
