<?php

namespace Drupal\mwrd_reservoir;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Site\Settings;

/**
 * Updates reservoir_data nodes from an external feed.
 */
class ReservoirSync {

  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected TimeInterface $time,
  ) {}

  /**
   * Runs from cron. Does nothing until an API URL is configured.
   */
  public function sync(): int {
    $url = Settings::get('mwrd_reservoir_api_url');
    if (!$url) {
      return 0;
    }
    // TODO when the Pravah/SCADA API is available:
    //  1. Fetch $url with \Drupal::httpClient() (add auth from Settings).
    //  2. json_decode the body.
    //  3. For each row call $this->applyReading($row['code'], $row['percent'], $row['status'] ?? NULL, $row['timestamp'] ?? NULL);
    //  4. Log failures with \Drupal::logger('mwrd_reservoir').
    return 0;
  }

  /**
   * Updates one dam by its code. Returns FALSE if the code is unknown.
   */
  public function applyReading(string $code, int $percent, ?string $status = NULL, ?int $timestamp = NULL): bool {
    $storage = $this->entityTypeManager->getStorage('node');
    $ids = $storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', 'reservoir_data')
      ->condition('field_dam_code', $code)
      ->range(0, 1)
      ->execute();
    if (!$ids) {
      return FALSE;
    }

    $node = $storage->load(reset($ids));
    $node->setNewRevision(FALSE);
    $node->set('field_live_storage', max(0, min(100, $percent)));
    if ($status !== NULL) {
      $node->set('field_dam_status', $status);
    }
    $node->set('field_last_updated', gmdate('Y-m-d\TH:i:s', $timestamp ?? $this->time->getRequestTime()));
    $node->save();
    return TRUE;
  }

}