<?php

final class SemiStructuredObjectTypeArchiveController
  extends SemiStructuredBaseController {

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

    $object_type = id(new SemiStructuredObjectTypeQuery())
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->executeOne();
    if (!$object_type) {
      return new Aphront404Response();
    }


    $view_uri = $object_type->getURI();

    if ($request->isFormPost()) {
      if ($object_type->isArchived()) {
        $new_status = SemiStructuredObjectType::STATUS_ACTIVE;
      } else {
        $new_status = SemiStructuredObjectType::STATUS_ARCHIVED;
      }

      $xactions = array();

      $xactions[] = id(new SemiStructuredObjectTypeTransaction())
        ->setTransactionType(
          SemiStructuredObjectTypeStatusTransaction::TRANSACTIONTYPE)
        ->setNewValue($new_status);

      id(new SemiStructuredObjectTypeTransactionEditor())
        ->setActor($viewer)
        ->setContentSourceFromRequest($request)
        ->setContinueOnNoEffect(true)
        ->setContinueOnMissingFields(true)
        ->applyTransactions($object_type, $xactions);

      return id(new AphrontRedirectResponse())->setURI($view_uri);
    }

    if ($object_type->isArchived()) {
      $title = pht('Activate Object Type');
      $body = pht('This Object Type will be usable again.');
      $button = pht('Activate Object Type');
    } else {
      $title = pht('Archive Object Type');
      $body = pht('This Object Type will be grayed out and forgotten.');
      $button = pht('Archive Object Type');
    }

    return $this->newDialog()
      ->setTitle($title)
      ->appendChild($body)
      ->addCancelButton($view_uri)
      ->addSubmitButton($button);
  }

}
