<?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
   */
  public $res;


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

  /**
   * The region of the page into which JavaScript will be loaded.
   *
   * @var String
   */
  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() {
    $modules = $this->angular->getModules();
    $page = $this; // PHP 5.3 does not propagate $this to inner functions.

    $this->res->addSettingsFactory(function () use (&$modules, $page) {
      // TODO optimization; client-side caching
      return array_merge($page->angular->getResources(array_keys($modules), 'settings', 'settings'), array(
        'resourceUrls' => \CRM_Extension_System::singleton()->getMapper()->getActiveModuleUrls(),
        'angular' => array(
          'modules' => array_merge(array('ngRoute'), array_keys($modules)),
          'cacheCode' => $page->res->getCacheCode(),
        ),
      ));
    });

    $this->res->addScriptFile('civicrm', 'bower_components/angular/angular.min.js', 100, $this->region, FALSE);

    $headOffset = 0;
    $config = \CRM_Core_Config::singleton();
    if ($config->debug) {
      foreach ($modules as $moduleName => $module) {
        foreach ($this->angular->getResources($moduleName, 'css', 'cacheUrl') as $url) {
          $this->res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->region);
        }
        foreach ($this->angular->getResources($moduleName, 'js', 'cacheUrl') as $url) {
          $this->res->addScriptUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->region);
          // addScriptUrl() bypasses the normal string-localization of addScriptFile(),
          // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
        }
      }
    }
    else {
      // Note: addScriptUrl() bypasses the normal string-localization of addScriptFile(),
      // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
      $aggScriptUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=js&r=' . $page->res->getCacheCode(), FALSE, NULL, FALSE);
      $this->res->addScriptUrl($aggScriptUrl, 120, $this->region);

      // FIXME: The following CSS aggregator doesn't currently handle path-adjustments - which can break icons.
      //$aggStyleUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=css&r=' . $page->res->getCacheCode(), FALSE, NULL, FALSE);
      //$this->res->addStyleUrl($aggStyleUrl, 120, $this->region);

      foreach ($this->angular->getResources(array_keys($modules), 'css', 'cacheUrl') as $url) {
        $this->res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->region);
      }
    }

    // If trying to load an Angular page via AJAX, the route must be passed as a
    // URL parameter, since the server doesn't receive information about
    // URL fragments (i.e, what comes after the #).
    \CRM_Core_Resources::singleton()->addSetting(array(
      'angularRoute' => \CRM_Utils_Request::retrieve('route', 'String'),
    ));
  }

}
