<?php

namespace Drupal\pagedesigner\Service;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\OutputTrait;
use Drupal\pagedesigner\PagedesignerServiceInterface;

/**
 * Applies changes of state to entity and pagedesigner content.
 */
class StateChanger implements StateChangerInterface {
  use OutputTrait;

  /**
   * Create a new instance.
   *
   * @param \Drupal\pagedesigner\PagedesignerServiceInterface $pagedesignerService
   *   The pagedesigner service.
   */
  public function __construct(
    protected PagedesignerServiceInterface $pagedesignerService,
  ) {

  }

  /**
   * {@inheritdoc}
   */
  public function publish(?ContentEntityBase $entity = NULL) {
    if ($entity == NULL) {
      return $this;
    }
    $fields = $this->pagedesignerService->getPagedesignerFields($entity);
    foreach ($fields as $field) {
      $container = $this->pagedesignerService->getContainer($entity, $field->getName());
      $this->output = $this->pagedesignerService->getHandler()->publish($container);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function unpublish(?ContentEntityBase $entity = NULL) {
    if ($entity == NULL) {
      return $this;
    }
    $fields = $this->pagedesignerService->getPagedesignerFields($entity);
    foreach ($fields as $field) {
      $container = $this->pagedesignerService->getContainer($entity, $field->getName());
      $this->output = $this->pagedesignerService->getHandler()->unpublish($container);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function copy(Element $entity, ?Element $container = NULL, ?Element $parent = NULL) {
    if ($entity == NULL) {
      return $this;
    }
    $clone = $this->pagedesignerService->getHandler()->copy($entity, $container);
    if (!empty($parent)) {
      $clone->parent->entity = $parent;
      $clone->save();
    }
    $this->output = $clone;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function generate(?ContentEntityBase $entity = NULL) {
    if ($entity == NULL) {
      return $this;
    }
    $this->output = $this->pagedesignerService->getContainer($entity)->id();
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function delete(?ContentEntityBase $entity = NULL) {
    if ($entity == NULL) {
      return $this;
    }
    $fields = $this->pagedesignerService->getPagedesignerFields($entity);
    foreach ($fields as $field) {
      $container = $this->pagedesignerService->getContainer($entity, $field->getName());
      $this->output = $this->pagedesignerService->getHandler()->delete($container);
    }
    return $this;
  }

}
