<?php

namespace Drupal\mwrd_reservoir\Controller;

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;

/**
 * Serves reservoir_data nodes as JSON for the homepage map.
 */
class ReservoirDataController extends ControllerBase {

  public function data(): CacheableJsonResponse {
    $storage = $this->entityTypeManager()->getStorage('node');
    $repo = \Drupal::service('entity.repository');

    $ids = $storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'reservoir_data')
      ->condition('status', 1)
      ->sort('title')
      ->execute();

    $cache = new CacheableMetadata();
    $cache->addCacheTags(['node_list:reservoir_data']);
    $cache->addCacheContexts(['languages:language_interface']);

    $dams = [];
    $sum = 0;
    foreach ($ids ? $storage->loadMultiple($ids) : [] as $node) {
      $node = $repo->getTranslationFromContext($node);
      if ($node->get('field_latitude')->isEmpty() || $node->get('field_longitude')->isEmpty()) {
        continue;
      }

      $district = NULL;
      if ($term = $node->get('field_district')->entity) {
        $term = $repo->getTranslationFromContext($term);
        $district = $term->label();
        $cache->addCacheableDependency($term);
      }

      $updated = NULL;
      if (!$node->get('field_last_updated')->isEmpty() && ($date = $node->get('field_last_updated')->date)) {
        $updated = $date->format('c');
      }

      $live = (int) $node->get('field_live_storage')->value;
      $sum += $live;

      $dams[] = [
        'id' => (int) $node->id(),
        'code' => $node->get('field_dam_code')->value,
        'name' => $node->label(),
        'river' => $node->get('field_river')->value,
        'district' => $district,
        'capacity' => (float) $node->get('field_capacity_tmc')->value,
        'live' => $live,
        'status' => $node->get('field_dam_status')->value ?: 'normal',
        'lat' => (float) $node->get('field_latitude')->value,
        'lng' => (float) $node->get('field_longitude')->value,
        'updated' => $updated,
      ];
    }

    $response = new CacheableJsonResponse([
      'average' => $dams ? (int) round($sum / count($dams)) : NULL,
      'dams' => $dams,
    ]);
    $response->addCacheableDependency($cache);
    return $response;
  }

}