<?php

namespace Drupal\languagewire_translation_provider\Client;

use Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentDocumentModel;
use Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentModel;
use Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentStatusModel;

/**
 * Adapter on API Assignment.
 */
class Assignment {

  /**
   * Status.
   *
   * @var AssignmentStatus
   *   Status.
   */
  private AssignmentStatus $status;

  /**
   * Document ID pairs.
   *
   * @var int[]
   *   Document ID pairs.
   */
  private array $documentIdPairs;

  /**
   * Constructs a new Assignment object.
   *
   * @param \Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentModel $assignment
   *   Assignment model.
   */
  public function __construct(AssignmentModel $assignment) {
    $this->status = AssignmentStatus::fromPlatformStatus($assignment->getStatus());
    $this->documentIdPairs = $this->getDocumentIdPairsFromPlatformAssignment($assignment);
  }

  /**
   * Status.
   */
  public function status(): AssignmentStatus {
    return $this->status;
  }

  /**
   * Is completed.
   *
   * @return int[]
   *   Document ID pairs.
   */
  public function getPlatformDocumentIdPairs(): array {
    return $this->documentIdPairs;
  }

  /**
   * Get document ID pairs from platform assignment.
   *
   * @return int[]
   *   Document ID pairs.
   */
  public function getDocumentIdPairsFromPlatformAssignment(AssignmentModel $assignment): array {
    $ids = [];

    foreach ($assignment->getDocuments() as $assignmentDocument) {
      /** @var \Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentDocumentModel $assignmentDocument */
      $ids[$assignmentDocument->getSourceDocumentId()] = $assignmentDocument->getTargetDocumentId();
    }

    return $ids;
  }

  /**
   * Transform platform files to assignments.
   *
   * @return \Drupal\languagewire_translation_provider\api\Models\Assignments\AssignmentModel[]
   *   Assignments.
   *
   * @throws \Exception
   */
  public static function fromPlatformFiles(array $files): array {
    $assignments = [];

    foreach ($files as $file) {
      foreach ($file['translations'] as $translation) {
        $assignmentDocument = new AssignmentDocumentModel($file['sourceFileId'], $translation['fileId']);

        // @todo Replace assignment id to real id
        $assignmentModel = new AssignmentModel(
          uniqid(),
          $file['sourceLanguage'],
          $translation['targetLanguage'],
          AssignmentStatusModel::fromString($translation['status']),
          [$assignmentDocument]
        );

        $assignments[] = new self($assignmentModel);
      }
    }

    return $assignments;
  }

}
