<?php

namespace Drupal\languagewire_translation_provider\Client;

use Drupal\languagewire_translation_provider\api\Models\Project\ProjectModel;
use Drupal\languagewire_translation_provider\api\Models\Project\ProjectStatusModel;
use Drupal\languagewire_translation_provider\Domain\Project;
use Drupal\languagewire_translation_provider\Domain\ProjectTemplate;

/**
 * Api Project Specification with project template.
 */
final class LanguageWireProjectFromTemplateSpecification implements ProjectSpecificationInterface {
  /**
   * Project.
   *
   * @var \Drupal\languagewire_translation_provider\Domain\Project
   */
  private Project $project;

  /**
   * Project template.
   *
   * @var \Drupal\languagewire_translation_provider\Domain\ProjectTemplate
   */
  private ProjectTemplate $projectTemplate;

  /**
   * Constructs a new LanguageWireProjectFromTemplateSpecification object.
   *
   * @param \Drupal\languagewire_translation_provider\Domain\Project $project
   *   Project template.
   * @param \Drupal\languagewire_translation_provider\Domain\ProjectTemplate $projectTemplate
   *   Project template.
   */
  public function __construct(
    Project $project,
    ProjectTemplate $projectTemplate
  ) {
    $this->project = $project;
    $this->projectTemplate = $projectTemplate;
  }

  /**
   * {@inheritdoc}
   */
  public function toSpecification(ClientInterface $client): ProjectModel {
    $projectName = $this->title();
    $translationMemoryID = $this->projectTemplate->getTranslationMemoryId();
    $termBaseID = $this->projectTemplate->getTermBaseId();

    $project = $this->project;

    $userID = $this->project->getTmgmtJob()->getUserId();
    if (empty($userID)) {
      $userID = $this->projectTemplate->getUserId();
    }

    $deliveryDate = $project->getTmgmtJob()->getDeadline();

    return ProjectModel::initialize(
      $project->getId(),
      $this->projectUuid(),
      !empty($projectName) ? $projectName : $this->projectTemplate->getProjectName(),
      $project->getTmgmtJob()->getBriefing(),
      (string) NULL,
      (string) NULL,
      $deliveryDate->format('Y-m-d'),
      $this->projectTemplate->getPlatformId(),
      NULL,
      $translationMemoryID === 0 ? NULL : $translationMemoryID,
      $termBaseID === 0 ? NULL : $termBaseID,
      $this->projectTemplate->getInvoicingAccountId(),
      $userID,
      $this->projectTemplate->getWorkAreaId(),
      ProjectStatusModel::initialize(ProjectStatusModel::DRAFT),
      'https://test'
    );
  }

  /**
   * {@inheritdoc}
   */
  public function projectUuid(): string {
    return $this->project->getCorrelationId();
  }

  /**
   * {@inheritdoc}
   */
  public function title(): string {
    return $this->project->getTmgmtJob()->title();
  }

}
