<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Cron\Job;

use Drupal\languagewire_translation_provider\Adapter\SystemInterface;
use Drupal\languagewire_translation_provider\Client\LanguageWireClientFactory;
use Drupal\languagewire_translation_provider\Database\ProjectRepositoryInterface;
use Drupal\languagewire_translation_provider\Domain\Project;
use Drupal\languagewire_translation_provider\Domain\ProjectStatus;
use Drupal\languagewire_translation_provider\Service\ProjectMonitor;

/**
 * Project Monitoring Job.
 */
final class ProjectMonitoringJob extends BaseJob {

  /**
   * Project monitor.
   *
   * @var \Drupal\languagewire_translation_provider\Service\ProjectMonitor
   */
  private ProjectMonitor $projectMonitor;

  /**
   * Constructs a new ProjectMonitoringJob object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\SystemInterface $system
   *   System.
   * @param \Drupal\languagewire_translation_provider\Database\ProjectRepositoryInterface $projectRepository
   *   Project repository.
   * @param \Drupal\languagewire_translation_provider\Client\LanguageWireClientFactory $clientFactory
   *   LanguageWire client factory.
   * @param \Drupal\languagewire_translation_provider\Service\ProjectMonitor $projectMonitor
   *   Project monitor.
   */
  public function __construct(
    SystemInterface $system,
    ProjectRepositoryInterface $projectRepository,
    LanguageWireClientFactory $clientFactory,
    ProjectMonitor $projectMonitor
  ) {
    parent::__construct($system, $projectRepository, $clientFactory);
    $this->projectMonitor = $projectMonitor;
  }

  /**
   * Get job name.
   */
  protected function jobName(): string {
    return "Project Monitoring";
  }

  /**
   * Get projects.
   *
   * @return \Drupal\languagewire_translation_provider\Domain\Project[]
   *   Projects.
   */
  protected function getProjects(): array {
    return $this->projectRepository->getAllByStatus(ProjectStatus::inProgress());
  }

  /**
   * Process project.
   *
   * @throws \Drupal\languagewire_translation_provider\api\Core\Exception\Error
   */
  protected function processProject(Project $project): void {
    $this->projectMonitor->monitorProject(
          $project,
          $this->getLanguageWireClient($project->getTmgmtJob())
      );
    $this->projectRepository->save($project);
  }

}
