<?php
namespace Civi\Angular\Page;

/**
 * This page is simply a container; any Angular modules defined by CiviCRM (or by CiviCRM extensions)
 * will be activated on this page.
 *
 * @link https://issues.civicrm.org/jira/browse/CRM-14479
 */
class Main extends \CRM_Core_Page {

  /**
   * The weight to assign to any Angular JS module files.
   */
  const DEFAULT_MODULE_WEIGHT = 200;

  /**
   * The resource manager.
   *
   * Do not use publicly. Inject your own copy!
   *
   * @var \CRM_Core_Resources
   * @deprecated
   */
  public $res;

  /**
   * The Angular module manager.
   *
   * Do not use publicly. Inject your own copy!
   *
   * @var \Civi\Angular\Manager
   * @deprecated
   */
  public $angular;

  /**
   * The region of the page into which JavaScript will be loaded.
   *
   * @var string
   * @deprecated
   */
  public $region;

  /**
   * @param string $title
   *   Title of the page.
   * @param int $mode
   *   Mode of the page.
   * @param \CRM_Core_Resources|null $res
   *   Resource manager.
   */
  public function __construct($title = NULL, $mode = NULL, $res = NULL) {
    parent::__construct($title, $mode);
    $this->res = \CRM_Core_Resources::singleton();
    $this->angular = \Civi::service('angular');
    $this->region = \CRM_Utils_Request::retrieve('snippet', 'String') ? 'ajax-snippet' : 'html-header';
  }

  /**
   * This function takes care of all the things common to all
   * pages. This typically involves assigning the appropriate
   * smarty variable :)
   *
   * @return string
   *   The content generated by running this page
   */
  public function run() {
    $this->registerResources();
    return parent::run();
  }

  /**
   * Register resources required by Angular.
   */
  public function registerResources() {
    $loader = new \Civi\Angular\AngularLoader();
    $loader->setPageName('civicrm/a');
    $loader->useApp([
      'activeRoute' => \CRM_Utils_Request::retrieve('route', 'String'),
      'defaultRoute' => NULL,
    ]);
    $loader->load();

  }

}
