<?php

/**
 * @file
 * Contains archibald_stats_node_field.
 */

class archibald_stats_node_field extends archibald_stats_base_field {

  /**
   * @{inheritdoc}
   */
  function render($values) {
    static $cache = array();

    $node = archibald_lomch_description_load_by_lom_id($values->lomId);

    if (empty($node)) {
      if (!empty($cache[$values->lomId])) {
        $node = $cache[$values->lomId];
      }
      else {
        $node = new stdClass();
        $partner_id = (int) $this->view->exposed_raw_input['partner'];
        // Fetch the description data from the API.
        try {
          $client = archibald_get_client_based_on_config($partner_id ? $partner_id : NULL);
          $data = $client->loadDescription($values->lomId);
          $lom = new \Educa\DSB\Client\Lom\LomDescription($data);
          $node->title = $lom->getTitle();
        }
        catch(Exception $e) {
          $node->title = t("Description !id not found (deleted?)", array(
            '!id' => $values->lomId,
          ));
        }
        $cache[$values->lomId] = $node;
      }
    }

    switch ($this->real_field) {
      case 'node_title':
        return empty($node->nid) ? check_plain($node->title) : l($node->title, "node/{$node->nid}");

      case 'node_nid':
      default:
        return empty($node->nid) ? 'n/a' : check_plain($node->nid);
    }
  }
}
