<?php

/**
 * The other methods expose the structure of the Extensions Store application,
 * this method exposes a more "wire"/"stable" format for the API.
 *
 * The primary workflows will use this method, to allow the Store application to
 * evolve more easily.
 */
final class ExtensionStoreQueryExtensionAPIMethod
  extends ConduitAPIMethod {

  public function getApplication() {
    return PhabricatorApplication::getByClass(
      ExtensionsStoreApplication::class);
  }

  public function getAPIMethodName() {
    return 'extensionstore.queryextension';
  }

  public function getMethodSummary(){
    return 'TODO';
  }

  public function getMethodDescription() {
    return 'e **TODO**';
  }


  /**
   * Whether to require a session key for calling the API method.
   *
   * @return bool Defaults to true
   */
  public function shouldRequireAuthentication() {
    return false;
  }


  /**
   * @return array Pairs of parameter name and their type
   */
  protected function defineParamTypes() {
    return array(
      'extensionKeys' => 'required list[string]',
    );
  }

  /**
   * @return string Human-readable text description of the return format,
   *   for example 'array<string,mixed> | null'
   */
   protected function defineReturnType() {
    return 'map of extensionKey to Extension Data';
   }

  protected function execute(ConduitAPIRequest $request) {
    $full_keys = $request->getValue('extensionKeys');

    $keys = array_map('ExtensionStoreExtensionKey::parseFullKey', $full_keys);
    $keys = array_filter($keys);

    $publisher_keys = ipull($keys, 'publisher');
    $extension_keys = ipull($keys, 'extension');

    if (!$publisher_keys || !$extension_keys) {
      return array();
    }

    $extensions = new ExtensionStoreExtensionQuery()
      ->setViewer($request->getViewer())
      ->withPublisherKeys($publisher_keys)
      ->withExtensionKeys($extension_keys)
      ->needPublishers(true)
      ->needLatestRelease(true)
      ->execute();

    $results = array();

    foreach ($extensions as $ext) {
      $result = $ext->toExtensionQueryResult($this->getViewer());
      if ($result) {
        $results[$ext->getFullExtensionKey()] = $result->toDictionary();
      }
    }

    // the above trickery may select some more results, remove them.
    return array_select_keys($results, $full_keys);
  }

}
