<?php

/**
 * @extends PhabricatorCursorPagedPolicyAwareQuery<ExtensionStoreRelease>
 */
final class ExtensionStoreReleaseQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $phids;
  private $extensionPHIDs;
  private $statuses;

  private ?ExtensionStoreExtension $extension = null;

  public function withIDs(array $ids) {
    $this->ids = $ids;
    return $this;
  }

  public function withPHIDs(array $phids) {
    $this->phids = $phids;
    return $this;
  }

  public function withExtension(ExtensionStoreExtension $extension) {
    $this->extension = $extension;
    return $this->withExtensionPHIDs(array($extension->getPHID()));
  }

  public function withExtensionPHIDs(array $phids) {
    $this->extensionPHIDs = $phids;
    return $this;
  }

  public function withStatuses(array $statuses) {
    $this->statuses = $statuses;
    return $this;
  }

  public function newResultObject() {
    return ExtensionStoreRelease::initializeNewRelease($this->getViewer());
  }

  protected function didFilterPage(array $items) {

    return $items;
  }

  protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
    $where = parent::buildWhereClauseParts($conn);

    if ($this->ids !== null) {
      $where[] = qsprintf(
        $conn,
        'releases.id IN (%Ld)',
        $this->ids);
    }

    if ($this->phids !== null) {
      $where[] = qsprintf(
        $conn,
        'releases.phid IN (%Ls)',
        $this->phids);
    }

    if ($this->extensionPHIDs !== null) {
      $where[] = qsprintf(
        $conn,
        'releases.extensionPHID IN (%Ls)',
        $this->extensionPHIDs);
    }

    if ($this->statuses !== null) {
      $where[] = qsprintf(
        $conn,
        'releases.status IN (%Ls)',
        $this->statuses);
    }

    return $where;
  }


  protected function willFilterPage(array $objects) {
    if ($this->extension) {
      foreach ($objects as $key => $object) {
        $object->attachExtension($this->extension);
      }
    }

    return $objects;
  }


  public function getQueryApplicationClass() {
    return ExtensionsStoreApplication::class;
  }

  protected function getPrimaryTableAlias() {
    return 'releases';
  }

}
