<?php

namespace Drupal\acquia_dam\Cron;

use Drupal\acquia_dam\AssetUpdater;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\CronInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Acquia DAM cron implementation.
 */
class Cron implements CronInterface {

  use StringTranslationTrait;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * A logger channel dedicated to updating media items.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $mediaItemUpdateLogger;

  /**
   * The asset updater service.
   *
   * @var \Drupal\acquia_dam\AssetUpdater
   */
  protected $assetUpdater;

  /**
   * Constructs a new Cron object.
   *
   * @param \Drupal\acquia_dam\AssetUpdater $assetUpdater
   *   The asset updater service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time.
   * @param \Drupal\Core\State\StateInterface $state
   *   State service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerChannelFactory
   *   Logger factory.
   */
  public function __construct(
    AssetUpdater $assetUpdater,
    TimeInterface $time,
    StateInterface $state,
    LoggerChannelFactoryInterface $loggerChannelFactory
  ) {
    $this->assetUpdater = $assetUpdater;
    $this->time = $time;
    $this->state = $state;
    $this->mediaItemUpdateLogger = $loggerChannelFactory->get('acquia_dam.media_item_update');
  }

  /**
   * {@inheritdoc}
   */
  public function run(): bool {
    try {
      $request_time = $this->time->getCurrentTime();
      $last_update = (int) $this->state->get('acquia_dam.last_update_check', 0);

      // Delegate to AssetUpdater service.
      $this->assetUpdater->syncAssets([
        'since-timestamp' => $last_update,
        'finalized-version' => FALSE,
      ]);

      $this->state->set('acquia_dam.last_update_check', $request_time);
    }
    catch (\Exception $exception) {
      $this->mediaItemUpdateLogger->warning(
        sprintf(
          'Something went wrong during DAM cron run. Error: %s',
          $exception->getMessage()
        ));

      return FALSE;
    }

    return TRUE;
  }

}
