<?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\ProjectImporter;

/**
 * Project Import Job.
* */
final class ProjectImportJob extends BaseJob {

  /**
   * Project importer.
   *
   * @var \Drupal\languagewire_translation_provider\Service\ProjectImporter
   */
  private ProjectImporter $projectImporter;

  /**
   * Constructs a new ProjectImportJob 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\ProjectImporter $projectImporter
   *   Project importer.
   */
  public function __construct(SystemInterface $system, ProjectRepositoryInterface $projectRepository, LanguageWireClientFactory $clientFactory, ProjectImporter $projectImporter) {
    parent::__construct($system, $projectRepository, $clientFactory);
    $this->projectImporter = $projectImporter;
  }

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

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

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

}
