<?php

final class SemiStructuredObjectTypeQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

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

  public function withIDs(array $ids) {
    $this->ids = $ids;
    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() {
    return new SemiStructuredObjectType();
  }

  // There might already be a similar solution in the Phorge code base.
  public static function loadOneById(PhabricatorUser $viewer, $id) {
    $viewer_key = $viewer->getCacheFragment();
    $cache = PhabricatorCaches::getRequestCache();
    $cache_key = self::class.'ById';

    $collection = $cache->getKey($cache_key, array());
    $value = idxv($collection, array($viewer_key, $id));

    if ($value) {
      return $value;
    }

    $value = (new self())
      ->setViewer($viewer)
      ->withIds(array($id))
      ->executeOne();

    $collection[$viewer_key][$id] = $value;
    $cache->setKey($cache_key, $collection);
    return $value;
  }

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

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

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

    return $where;
  }

  public function getQueryApplicationClass() {
    return 'SemiStructuredDataApplication';
  }

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

}
