/**
 * Copyright © 2012-2016 by Data Virtuality GmbH
 */
// https://issues.redhat.com/browse/TEIID-6032
package org.teiid.translator.salesforce.execution.visitors;

import org.teiid.language.ColumnReference;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.salesforce.SalesForceExecutionFactory;

/**
 * @author Sachin Pattan
 * @date 04.05.2016
 * 
 *       Class for adding the IsDeleted clause on all the select statements if the same is configured as translator
 *       property.
 */
public class SelectVisitorWithExecutionFactory extends SelectVisitor {

	private SalesForceExecutionFactory salesForceExecutionFactory;

	/**
	 * @param metadata
	 * @param salesForceExecutionFactory
	 */
	public SelectVisitorWithExecutionFactory(RuntimeMetadata metadata, SalesForceExecutionFactory salesForceExecutionFactory) {
		super(metadata);
		this.salesForceExecutionFactory = salesForceExecutionFactory;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.teiid.translator.salesforce.execution.visitors.SelectVisitor#getQuery()
	 */
	@Override
	public String getQuery() throws TranslatorException {
		if (table.getColumnByName("IsDeleted") != null && salesForceExecutionFactory.isForceExcludeDeleted()) {
			// check if there is already a criteria on IsDeleted. If yes, skip adding the condition.
			for (String criteria : criteriaBuffer) {
				if (criteria.contains("IsDeleted")) {
					return super.getQuery();
				}
			}
			String condition = table.getSourceName() + "." + table.getColumnByName("IsDeleted").getName() + "="
					+ false;
			String criteria = criteriaBuffer.size() != 0 ? " and " + condition : condition;
			criteriaBuffer.add(criteria);
			setHasCriteria(false);
		}
		return super.getQuery();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.teiid.translator.salesforce.execution.visitors.SelectVisitor#canRetrieve()
	 */
	@Override
	public boolean canRetrieve() {
		return super.canRetrieve() && !salesForceExecutionFactory.isForceExcludeDeleted();
	}

	@Override
	void appendColumnReference(StringBuilder queryString, ColumnReference ref) {
		if (salesForceExecutionFactory.isUseTableAliasForColumns()) {
			super.appendColumnReference(queryString, ref);
		} else {
			queryString.append(ref.getMetadataObject().getSourceName());
		}
	}

}
