<?php
/**
 * Copyright (C) 2023  Jaap Jansma (jaap.jansma@civicoop.org)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace Civi\DataProcessor\DataFlow\SqlDataFlow;

use Civi\DataProcessor\DataFlow\SqlTableDataFlow;
use Civi\DataProcessor\DataSpecification\SqlFieldSpecification;

class SqlQueryDataFlow extends SqlTableDataFlow {

  /**
   * @var string
   */
  protected $query;

  public function __construct(string $query, string $table_alias) {
    $this->query = $query;
    $this->table_alias = $table_alias;
  }

  public function getName(): string {
    return $this->table_alias;
  }

  /**
   * @param string $query
   */
  public function setQuery(string $query) {
    $this->query = $query;
  }

  /**
   * @param $table_alias
   *
   * @return \Civi\DataProcessor\DataFlow\SqlDataFlow\SqlQueryDataFlow
   */
  public function setTableAlias($table_alias): SqlQueryDataFlow {
    $this->table_alias = $table_alias;
    return $this;
  }

  /**
   * Returns the Table part in the from statement.
   *
   * @return string
   */
  public function getTableStatement(): string {
    return "($this->query) `$this->table_alias`";
  }

  /**
   * Returns an array with the fields for in the select statement in the sql query.
   *
   * @param bool $isCountQuery
   * @return string[]
   */
  public function getFieldsForSelectStatement(bool $isCountQuery=false): array {
    $fields = array();
    foreach($this->getDataSpecification()->getFields() as $field) {
      if ($field instanceof SqlFieldSpecification) {
        $fields[] = $field->getSqlSelectStatement($this->table_alias, $isCountQuery);
      } else {
        $fields[] = "`$this->table_alias`.`$field->name` AS `$field->alias`";
      }
    }
    return $fields;
  }

}
