<?php

final class SemiStructuredObjectInstanceListController
  extends SemiStructuredObjectInstanceController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();

    $object_type = SemiStructuredObjectTypeQuery::loadOneById(
      $viewer,
      $request->getURIData('typeid'));
    if (!$object_type) {
      return new Aphront404Response();
    }
    $this->setObjectType($object_type);


    $query_key = $request->getURIData('queryKey');
    $controller = id(new PhabricatorApplicationSearchController())
      ->setQueryKey($query_key)
      ->setSearchEngine(
        id(new SemiStructuredObjectInstanceSearchEngine())
          ->setObjectType($object_type))
      ->setNavigation($this->buildSideNavView());

    return $this->delegateToController($controller);
  }

  public function buildSideNavView($filter = null) {
    $user = $this->getRequest()->getUser();

    $nav = new AphrontSideNavFilterView();
    $nav->setBaseURI(new PhutilURI($this->getApplicationURI()));

    id(new SemiStructuredObjectInstanceSearchEngine())
      ->setObjectType($this->getObjectType())
      ->setViewer($user)
      ->addNavigationItems($nav->getMenu());

    $nav->selectFilter($filter);

    return $nav;
  }

  protected function buildApplicationCrumbs() {
    $crumbs = parent::buildApplicationCrumbs();

    $object_type = $this->getObjectType();

    id(new SemiStructuredObjectInstanceEditEngine())
      ->setObjectType($object_type)
      ->setViewer($this->getViewer())
      ->addActionToCrumbs($crumbs);

    return $crumbs;
  }
}
