<?php

final class SemiStructuredObjectInstanceQuery
  extends PhabricatorCursorPagedPolicyAwareQuery {

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

  private ?SemiStructuredObjectType $objectType = null;

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

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

  public function withObjectType(SemiStructuredObjectType $object_type) {
    $this->objectType = $object_type;
    return $this->withClassPHIDs(array($object_type->getPHID()));
  }

  public function withClassPHIDs(array $class_phids) {
    $this->classPHIDs = $class_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 SemiStructuredObjectInstance();
    if ($this->objectType) {
      $instance->attachClass($this->objectType);
    }
    return $instance;
  }

  protected function didFilterPage(array $items) {

    $phids = mpull($items, 'getPHID');

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

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

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

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

    return $where;
  }

  protected function willFilterPage(array $objects) {
    $classes = id(new SemiStructuredObjectTypeQuery())
      ->setViewer($this->getViewer())
      ->withPHIDs(mpull($objects, 'getClassPHID'))
      ->execute();

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

    foreach ($objects as $key => $object) {
      $class = idx($classes, $object->getClassPHID());
      if (!$class) {
        unset($objects[$key]);
        continue;
      }
      $object->attachClass($class);
    }

    return $objects;
  }


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

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

}
