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

namespace Civi\DataProcessor\Utils;

use Civi\DataProcessor\DataFlow\SqlDataFlow\WhereClauseInterface;

class Sql {

  public static function convertTypeToSqlColumnType($strType) {
    switch($strType) {
      case 'Integer':
      case 'Int':
      case 'Timestamp':
        return 'INT (11)';
        break;
      case 'String':
      case 'Text':
      case 'Email':
        return 'TEXT';
        break;
      case 'Date':
        return 'DATE';
        break;
      case 'Time':
        return 'TIME';
        break;
      case 'Boolean':
        return 'TINYINT (1)';
        break;
      case 'Blob':
      case 'Mediumblob':
        return 'Blob';
        break;
      case 'Float':
      case 'Money':
        return 'FLOAT';
        break;
    }
    throw new \Exception('Invalid type given: '.$strType);
  }

  public static function generateConditionStatement(array $clauses = []): string {
    $andClauses = array("1");
    $orClauses = [];
    /** @var WhereClauseInterface $previousClause */
    $previousClause = null;
    /** @var WhereClauseInterface $clause */
    foreach($clauses as $clause) {
      if ($clause->isOR() && $previousClause) {
        $orClauses[] = $previousClause->getWhereClause();
      } elseif (!$clause->isOR() && $previousClause && $previousClause->isOR()) {
        $orClauses[] = $previousClause->getWhereClause();
        $andClauses[] = '(' . implode(" OR ", $orClauses).')';
        $orClauses = [];
        $andClauses[] = $clause->getWhereClause();
      } elseif (!$clause->isOR() && $previousClause && !$previousClause->isOR()) {
        $andClauses[] = $previousClause->getWhereClause();
      }
      $previousClause = $clause;
    }
    if ($previousClause && $previousClause->isOR()) {
      $orClauses[] = $previousClause->getWhereClause();
      $previousClause = null;
    }
    if (count($orClauses)) {
      $andClauses[] = '(' . implode(" OR ", $orClauses).')';
    }
    if ($previousClause && !$previousClause->isOR()) {
      $andClauses[] = $previousClause->getWhereClause();
    }
    if (count($andClauses)) {
      return implode(" AND ", $andClauses);
    }
    return "";
  }

}
