<?php

/**
 * @extends PhabricatorCursorPagedPolicyAwareQuery<ExtensionStorePublisher>
 */
final class ExtensionStorePublisherQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $keys;
  private $phids;
  private $statuses;
  private $canEdit;

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

  public function withKeys(array $keys) {
    $this->keys = $keys;
    return $this;
  }

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

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


  public function withCanEdit($can_edit) {
    $this->canEdit = $can_edit;
    return $this;
  }

  public function newResultObject() {
    $instance = new ExtensionStorePublisher();

    return $instance;
  }

  protected function didFilterPage(array $items) {

    if ($this->canEdit) {
      $items = id(new PhabricatorPolicyFilter())
        ->setViewer($this->getViewer())
        ->requireCapabilities(array(
          PhabricatorPolicyCapability::CAN_EDIT,
        ))
        ->apply($items);
    }

    return $items;
  }

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

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

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

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

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

    return $where;
  }

  protected function willFilterPage(array $objects) {

    return $objects;
  }


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

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

  public static function loadOneById($id, $viewer): ?ExtensionStorePublisher {
    return new self()
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->executeOne();
  }
}
