<?php

/**
 * @extends PhabricatorCursorPagedPolicyAwareQuery<ExtensionStoreExtension>
 */
final class ExtensionStoreExtensionQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

  private $ids;
  private $phids;
  private $publisherPHIDs;
  private $extensionKeys;
  private $publisherKeys;
  private $statuses;
  private $canEdit;

  private ?ExtensionStorePublisher $publisher = null;

  private $needPublishers = false;
  private $needLatestRelease = false;

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

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

  public function withPublisher(ExtensionStorePublisher $publisher) {
    $this->publisher = $publisher;
    return $this->withPublisherPHIDs(array($publisher->getPHID()));
  }

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

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

  public function withExtensionKeys(array $keys) {
    $this->extensionKeys = $keys;
    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 needPublishers($need) {
    $this->needPublishers = $need;
    return $this;
  }

  public function needLatestRelease($need) {
    $this->needLatestRelease = $need;
    return $this;
  }

  public function newResultObject() {
    $instance = new ExtensionStoreExtension();
    return $instance;
  }

  private function shouldJoinPublishers() {
    return $this->publisherKeys !== null;
  }

  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,
        'extensions.id IN (%Ld)',
        $this->ids);
    }

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

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

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

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

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

    return $where;
  }

  protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
    $join = parent::buildJoinClauseParts($conn);

    if ($this->shouldJoinPublishers()) {
      $join[] = qsprintf(
        $conn,
        'JOIN %T publishers ON publishers.phid = extensions.publisherPHID',
        new ExtensionStorePublisher()->getTableName());
    }

    return $join;
  }

  protected function willFilterPage(array $objects) {
    if ($this->needPublishers) {
      $publishers = new PhabricatorObjectQuery()
        ->setViewer($this->getViewer())
        ->setParentQuery($this)
        ->withPHIDs(mpull($objects, 'getPublisherPHID'))
        ->withTypes(array(ExtensionStorePublisherPHIDType::TYPECONST))
        ->execute();

      $publishers = mpull($publishers, null, 'getPHID');

      foreach ($objects as $key => $object) {
        $publisher = idx($publishers, $object->getPublisherPHID());
        if (!$publisher) {
          unset($objects[$key]);
          continue;
        }
        $object->attachPublisher($publisher);
      }
    } else if ($this->publisher) {
      foreach ($objects as $key => $object) {
        $object->attachPublisher($this->publisher);
      }
    }

    if ($this->needLatestRelease) {
      // This is a very poor way to implement "find latest release", but I want
      // to get on with other things
      $releases = new ExtensionStoreReleaseQuery()
        ->setViewer($this->getViewer())
        ->setParentQuery($this)
        ->withExtensionPHIDs(mpull($objects, 'getPHID'))
        ->setOrder('oldest')
        ->execute();

      $release_by_extension = mpull($releases, null, 'getExtensionPHID');
      foreach ($objects as $key => $object) {
        $release = idx($release_by_extension, $object->getPHID());
        if (!$release) {
          $object->attachLatestRelease($release);
          continue;
        }
        $object->attachLatestRelease($release);
        $release->attachExtension($object);
      }
    }

    return $objects;
  }


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

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

}
