<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\CronJob;

class CronJobCompositor implements ICronJob
{
  
  private $cronjobs;

  public function __construct(ICronJob ... $cronjobs)
  {
    $this->cronjobs = $cronjobs;
  }

  public function getTimeInterval(CronJobStorage $storage): ?int
  {
    $result = null;
    foreach ($this->cronjobs as $cronjob) {
      $cronjobTimeInterval = $cronjob->getTimeInterval($storage);
      if (is_null($result)) {
        $result = $cronjobTimeInterval;
      } elseif (!is_null($cronjobTimeInterval)) {
        $result = min($cronjobTimeInterval, $result);
      }
    }

    return $result;
  }

  public function execute(CronJobStorage $storage): void
  {
    $timeNowInSeconds = (int)(\DateTimeOperations::getTimestampNow() / 60);

    foreach ($this->cronjobs as $cronjob) {
      if (is_null($cronjob->getId())) {
        $cronjob->execute($storage);

        continue;
      }

      $cronjobTimeInterval = $cronjob->getTimeInterval($storage);
      
      
      
      $cronjobLastExecution = $storage->getLastExecutionTime($cronjob->getId());
      if (!is_null($cronjobTimeInterval)
        && (is_null($cronjobLastExecution) || (($timeNowInSeconds - $cronjobLastExecution) >= $cronjobTimeInterval))) {
        try {
          $cronjob->execute($storage);
          $storage->setLastExecutionTime($cronjob->getId());
        } catch (\Exception $ex) {
          \Logger::loggException($ex, 100);
        }
      }
    }
  }

  public function getName(): string
  {
    return implode(', ', array_map(static function(ICronJob $cronJob) {
      return $cronJob->getName();
    }, $this->cronjobs));
  }

  public function getId(): ?int
  {
    return null;
  }
}