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

namespace Civi\DataProcessor\DataFlow\SqlDataFlow;

class OrClause extends AbstractWhereClause implements WhereClauseInterface {

  /**
   * @var WhereClauseInterface[]
   */
  protected $clauses = array();

  /**
   * OrClause constructor.
   *
   * @param WhereClauseInterface[] $clauses
   */
  public function __construct(array $clauses=array(), bool $isJoinClause=FALSE) {
    $this->isJoinClause = $isJoinClause;
    $this->clauses = $clauses;
  }

  /**
   * Add a where clause to this clause
   *
   * @param \Civi\DataProcessor\DataFlow\SqlDataFlow\WhereClauseInterface $clause
   */
  public function addWhereClause(WhereClauseInterface $clause) {
    foreach($this->clauses as $c) {
      if (spl_object_id($clause) == spl_object_id($c) || $clause->getWhereClause() == $c->getWhereClause()) {
        return;
      }
    }
    $this->clauses[] = $clause;
  }

  public function hasWhereClauses(): bool {
    if (count($this->clauses)) {
      return true;
    }
    return false;
  }

  /**
   * Returns the where clause
   * E.g. contact_type = 'Individual'
   *
   * @return string
   */
  public function getWhereClause(): string {
    if (count($this->clauses)) {
      $clauses = array();
      foreach($this->clauses as $clause) {
        $clauses[] = "(". $clause->getWhereClause() . ")";
      }
      return "(" . implode(" OR ", $clauses) . ")";
    }
    return "1";
  }

  public function removeWhereClause(WhereClauseInterface $clause) {
    foreach($this->clauses as  $i => $c) {
      if (spl_object_id($clause) == spl_object_id($c) || $clause->getWhereClause() == $c->getWhereClause()) {
        unset($this->clauses[$i]);
      }
    }
  }

}
