<?php

final class ExtensionStorePublisherSearchEngine
  extends PhabricatorApplicationSearchEngine {

  public function getResultTypeDescription() {
    return pht('Extension publishers');
  }

  public function newQuery() {
    $query = new ExtensionStorePublisherQuery();
    return $query;
  }

  protected function buildCustomSearchFields() {

    return array(
      id(new PhabricatorSearchCheckboxesField())
        ->setKey('statuses')
        ->setLabel(pht('Status'))
        ->setOptions(ExtensionStorePublisherStatus::getStatusNameMap()),
      id(new PhabricatorSearchCheckboxesField())
        ->setKey('editable')
        ->setLabel(pht('Editable'))
        ->setOptions(array('editable' => null)),
    );
  }

  protected function getURI($path) {
    return "/extensionstore/publisher/{$path}";
  }

  public function getBuiltinQueryNames() {
    $names = array();

    $names['all'] = pht('All Publishers');
    // active ?

    return $names;
  }


  public function buildSavedQueryFromBuiltin($query_key) {
    $query = $this->newSavedQuery();
    $query->setQueryKey($query_key);

    switch ($query_key) {
      case 'all':
        return $query;
      // case 'open':
      //   return $query->setParameter(
      //     'statuses',
      //     array(
      //       ExtensionStorePublisher::STATUS_ACTIVE,
      //     ))

    }

    return parent::buildSavedQueryFromBuiltin($query_key);
  }

  protected function buildQueryFromParameters(array $map) {
    $query = $this->newQuery();

    if ($map['statuses']) {
      $query->withStatuses($map['statuses']);
    }

    if ($map['editable'] !== null) {
      $query->withCanEdit($map['editable']);
    }

    return $query;
  }

  protected function getRequiredHandlePHIDsForResultList(
    array $objects,
    PhabricatorSavedQuery $query) {

    return array();
  }

  protected function renderResultList(
    array $items,
    PhabricatorSavedQuery $query ,
    array $handles) {

    $viewer = $this->requireViewer();

    if ($items) {
      $edge_query = id(new PhabricatorEdgeQuery())
        ->withSourcePHIDs(mpull($items, 'getPHID'))
        ->withEdgeTypes(
          array(
            PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
          ));

      $edge_query->execute();
    }

    $list = id(new PHUIObjectItemListView())
      ->setViewer($viewer);

    foreach ($items as $publisher) {
      $item = id(new PHUIObjectItemView())
        ->setViewer($viewer)
        ->setHeader($publisher->getName())
        ->setHref($publisher->getURI())
        ->setObject($publisher);

      // $icon = id(new PHUIIconView())
      //   ->setIcon($publisher->getIcon());
      // $item->setImageIcon($icon);

      $phid = $publisher->getPHID();
      $project_phids = $edge_query->getDestinationPHIDs(array($phid));
      $project_handles = $viewer->loadHandles($project_phids);

      $item->addAttribute(
        id(new PHUIHandleTagListView())
          ->setLimit(4)
          ->setNoDataString(pht('No Tags'))
          ->setSlim(true)
          ->setHandles($project_handles));

/// TODO FLAGS

      $can_edit = PhabricatorPolicyFilter::hasCapability(
        $viewer,
        $publisher,
        PhabricatorPolicyCapability::CAN_EDIT);

      $edit_uri = $this->getApplicationURI(
        "/publisher/{$publisher->getId()}/edit/");
      $item->addAction((new PHUIListItemView())
          ->setName(pht('Edit'))
          ->setIcon('fa-edit')
          ->setDisabled(!$can_edit)
          ->setHref($edit_uri));

      $list->addItem($item);
    }

    $result = new PhabricatorApplicationSearchResultView();
    $result->setObjectList($list);
    $result->setNoDataString(pht('No publishers found.'));

    return $result;
  }

/* -(  Export   )------------------------------------------------------------ */

  protected function newExportFields() {
    return array(
      id(new PhabricatorStringExportField())
        ->setKey('name')
        ->setLabel(pht('Name')),
      id(new PhabricatorStringExportField())
        ->setKey('description')
        ->setLabel(pht('Description')),
      id(new PhabricatorStringExportField())
        ->setKey('rawData')
        ->setLabel(pht('Raw Data')),
      id(new PhabricatorPHIDExportField())
        ->setKey('publisherPHID')
        ->setLabel(pht('Class PHID')),
      id(new PhabricatorURIExportField())
        ->setKey('uri')
        ->setLabel(pht('URI')),
    );
  }

  protected function newExportData(array $publishers) {
    $export = array();
    foreach ($publishers as $publisher) {

      $export[] = array(
        'name' => $publisher->getName(),
        'uri' => PhabricatorEnv::getProductionURI($publisher->getURI()),
        'description' => $publisher->getDescription(),
        'publisherPHID' => $publisher->getPublisherPHID(),
        'rawData' => $publisher->getRawData(),
      );
    }

    return $export;
  }

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


}
