<?php

final class SemiStructuredObjectInstanceRawDataTransaction
  extends SemiStructuredObjectInstanceTransactionType {

  const TRANSACTIONTYPE = 'semist:instance:rawdata';

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

  public function applyInternalEffects($object, $value) {
    // TODO this might need changing ?
    $object->setRawData($value);
  }

  public function getTitle() {
    return pht(
      '%s updated the content of the object.',
      $this->renderAuthor());
  }

  public function getTitleForFeed() {
    return pht(
      '%s updated the content for object %s.',
      $this->renderAuthor(),
      $this->renderObject());
  }

  public function getMailDiffSectionHeader() {
    return pht('CHANGES TO CONTENT OF OBJECT INSTANCE');
  }

  public function hasChangeDetailView() {
    return true;
  }

  public function newChangeDetailView() {
    $viewer = $this->getViewer();

    $old = $this->getOldValue();
    $new = $this->getNewValue();

    $json = new PhutilJSON();
    // $old_json = $json->encodeFormatted($old);
    // $new_json = $json->encodeFormatted($new);

    return id(new PhabricatorApplicationTransactionTextDiffDetailView())
      ->setViewer($viewer)
      ->setOldText($old)
      ->setNewText($new);
  }


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

    if (!$xactions) {
      return $errors;
    }

    $json_parser = new PhutilJSONParser();

    if ($this->isEmptyTextTransaction($object->getRawData(), $xactions)) {
      $errors[] = $this->newRequiredError(
        pht('Object must have content.'));
    }

    foreach ($xactions as $xaction) {
      $new_value = $xaction->getNewValue();

      try {
        phutil_json_decode($new_value);
      } catch (PhutilJSONParserException $ex) {
        $errors[] = $this->newInvalidError(
          pht('Object body must be valid json!'));
      }
    }

    return $errors;
  }

}
