<?php

final class ExtensionStoreReleaseNameTransaction
  extends ExtensionStoreReleaseTransactionType {

  const TRANSACTIONTYPE = 'est:release:name';

  public function generateOldValue($object) {
    return $object->getName();
  }

  public function applyInternalEffects($object, $value) {
    $object->setName($value);
  }

  public function getTitle() {
    return pht(
      '%s changed the name of this release from %s to %s.',
      $this->renderAuthor(),
      $this->renderOldValue(),
      $this->renderNewValue());
  }

  public function getTitleForFeed() {
    return pht(
      '%s updated the name for %s from %s to %s.',
      $this->renderAuthor(),
      $this->renderObject(),
      $this->renderOldValue(),
      $this->renderNewValue());
  }

  public function validateTransactions($object, array $xactions) {
    $errors = array();

    if ($this->isEmptyTextTransaction($object->getName(), $xactions)) {
      $errors[] = $this->newRequiredError(
        pht('Releases must have a name (version).'));
      return $errors;
    }

    foreach ($xactions as $xaction) {
      $value = $xaction->getNewValue();
      $message = $this->validateName($value);
      if ($message) {
        $errors[] = $this->newInvalidError($message, $xaction);
      }
    }

    if (!$this->isNewObject()) {
      foreach ($xactions as $xaction) {
        $errors[] = $this->newInvalidError(
          pht(
            'Once a release is created, its name (version) cannot be changed.'),
          $xaction);
      }
    }

    return $errors;
  }

  private function validateName($name) {
    static $re = '/^\d+\.\d+(\.\d+)?(-[\w]+$)?/';
    if (!preg_match($re, $name)) {
      return pht('This is the regex used to validate version names: %s', $re);
    }
  }
}
