<?php

/** Management view of Extension */
final class ExtensionStoreExtensionManageController
  extends ExtensionStoreBaseController {

  use ExtensionStoreExtensionControllerTrait;

  public function handleRequest(AphrontRequest $request) {
    $extension = $this->findExtension($request);
    if (!$extension) {
      return new Aphront404Response();
    }

    $this->setExtension($extension);
    $publisher = $this->getPublisher();

    $crumbs = $this->buildApplicationCrumbs();
    $title = pht(
      '%s: %s %s',
      $publisher->getName(),
      $extension->getExtensionKey(),
      $extension->getName());

    $header = $this->buildHeaderView();
    $curtain = $this->buildCurtain();
    $details = $this->buildDetailsView();

    $timeline = $this->buildTransactionTimeline(
      $extension,
      new ExtensionStoreExtensionTransactionQuery());

    $view = id(new PHUITwoColumnView())
      ->setHeader($header)
      ->setCurtain($curtain)
      ->setMainColumn(array(
          $timeline,
        ))
      ->addPropertySection(pht('Details'), $details);

    return $this->newPage()
      ->setTitle($title)
      ->setCrumbs($crumbs)
      ->setPageObjectPHIDs(array($extension->getPHID()))
      ->appendChild($view);
  }


  private function buildCurtain() {
    $viewer = $this->getViewer();
    $extension = $this->getExtension();
    $publisher_key = $this->getPublisher()->getPublisherKey();

    $id = $extension->getID();
    $extension_key = $extension->getExtensionKey();

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

    $edit_uri = $this->getApplicationURI("/extension/edit/{$id}/");
    $store_uri = $this->getStoreUri("/e/{$publisher_key}/{$extension_key}");
    $create_release_uri = $this->getApplicationURI("/extension/publish/{$id}/");

    $curtain = $this->newCurtainView($extension);

      // view in store
    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('View In Store'))
        ->setIcon('fa-cart-plus')
        ->setHref($store_uri));

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('Edit Extension'))
        ->setIcon('fa-pencil')
        ->setDisabled(!$can_edit)
        ->setHref($edit_uri));

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('Publish Release'))
        ->setIcon('fa-gift')
        ->setDisabled(!$can_edit)
        ->setHref($create_release_uri));

    return $curtain;
  }


  protected function buildApplicationCrumbs() {

    $crumbs = parent::buildApplicationCrumbs();
    $this->addApplicationCrumbsSection($crumbs);
    return $crumbs;
  }
}
