<?php

namespace Drupal\pagedesigner_frontendpublishing\Plugin\frontendpublishing\StateChange;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\frontendpublishing\Plugin\frontendpublishing\StateChange\Standard;

/**
 * Reacts to state changes of nodes and alters the pagedesigner content.
 *
 * @StateChangeHandler(
 *   id = "pagedesigner",
 *   name = @Translation("Pagedesigner publisher"),
 *   weight = 200
 * )
 */
class Pagedesigner extends Standard {

  /**
   * Set the pagedesigner content to published.
   *
   *   The entity being published.
   */
  public function publish(ContentEntityBase &$entity) {
    \Drupal::service('pagedesigner.service.statechanger')->publish($entity);
    $this->updateEntityDate($entity);
  }

  /**
   * Placeholder to confirm to interface, transition is done in module file.
   *
   *   The entity being transitioned.
   *
   * @see pagedesigner_frontendpublishing.module
   */
  public function transition(ContentEntityBase &$entity) {
    $this->updateEntityDate($entity);
  }

  /**
   * Set the pagedesigner content to unpublished.
   *
   *   The entity being unpublished.
   */
  public function unpublish(ContentEntityBase &$entity) {
    \Drupal::service('pagedesigner.service.statechanger')->unpublish($entity);
    $this->updateEntityDate($entity);
  }

  /**
   * Copy the pagedesigner content from original entity to cloned entity.
   *
   *   The original entity.
   *   The cloned entity.
   */
  public function copy(ContentEntityBase &$entity, ?ContentEntityBase &$clone = NULL) {
    \Drupal::service('pagedesigner.service')->overrideContainers($clone);
    foreach ($clone->getTranslationLanguages(TRUE) as $language) {
      \Drupal::service('pagedesigner_duplication.service.duplicator')->duplicate($entity->getTranslation($language->getId()), $clone->getTranslation($language->getId()));
    }
  }

  /**
   * Generate the pagedesigner tree for a new entity.
   *
   *   The entity being generated.
   */
  public function generate(ContentEntityBase &$entity) {
    \Drupal::service('pagedesigner.service.statechanger')->generate($entity);
  }

  /**
   * Delete the pagedesigner tree for a new entity.
   *
   *   The entity being deleted.
   */
  public function delete(ContentEntityBase &$entity) {
    \Drupal::service('pagedesigner.service.statechanger')->delete($entity);
  }

  /**
   * Update the entity date.
   *
   *   The entity being updated.
   */
  private function updateEntityDate(ContentEntityBase &$entity) {
    $entity->set('changed', \Drupal::time()->getRequestTime());
    $entity->save();
  }

}
