<?php
/**
 * @author Jaap Jansma <jaap.jansma@civicoop.org>
 * @license AGPL-3.0
 */

namespace Civi\DataProcessor\FilterHandler;

use Civi\DataProcessor\DataFlow\CombinedDataFlow\CombinedSqlDataFlow;
use Civi\DataProcessor\DataFlow\InMemoryDataFlow;
use Civi\DataProcessor\DataFlow\SqlDataFlow;
use Civi\DataProcessor\DataFlow\SqlTableDataFlow;
use Civi\DataProcessor\DataSpecification\CustomFieldSpecification;
use Civi\DataProcessor\Exception\InvalidConfigurationException;
use Civi\DataProcessor\Source\AbstractCivicrmEntitySource;
use CRM_Dataprocessor_ExtensionUtil as E;

class SimpleSqlFilter extends AbstractFieldFilterHandler {

  /**
   * @param array $filter
   *   The filter settings
   * @return mixed
   */
  public function setFilter($filter) {
    $this->resetFilter();
    $dataFlow  = $this->dataSource->ensureField($this->inputFieldSpecification);
    if ($dataFlow && $dataFlow instanceof SqlDataFlow && $this->filterCollection->useWhere()) {
      $tableAlias = $this->getTableAlias($dataFlow);
      $fieldName = $this->inputFieldSpecification->getName();
      if ($this->isMultiValueField()) {
        $this->whereClause = new SqlDataFlow\MultiValueFieldWhereClause($tableAlias, $fieldName, $filter['op'], $filter['value'], $this->inputFieldSpecification->type);
      } else {
        $this->whereClause = new SqlDataFlow\SimpleWhereClause($tableAlias, $fieldName, $filter['op'], $filter['value'], $this->inputFieldSpecification->type);
      }
      $this->filterCollection->addWhere($this->whereClause);
    } elseif ($dataFlow && $dataFlow instanceof InMemoryDataFlow && !$this->isMultiValueField()) {
      $this->filterClass = new InMemoryDataFlow\SimpleFilter($this->inputFieldSpecification->getName(), $filter['op'], $filter['value']);
      $this->filterCollection->addFilter($this->filterClass);
    }
  }

  /**
   * @return bool
   */
  protected function isMultiValueField() {
    if ($this->fieldSpecification instanceof CustomFieldSpecification) {
      if ($this->fieldSpecification->isMultiple()) {
        return TRUE;
      }
    } elseif ($this->fieldSpecification->isMultiValueField()) {
      return TRUE;
    }
    return false;
  }

  /**
   * Returns true when this filter has additional configuration
   *
   * @return bool
   */
  public function hasConfiguration() {
    return true;
  }

  /**
   * When this filter type has configuration specify the template file name
   * for the configuration form.
   *
   * @return false|string
   */
  public function getConfigurationTemplateFileName() {
    return "CRM/Dataprocessor/Form/Filter/Configuration/SimpleSqlFilter.tpl";
  }


}
