<?php

namespace Drupal\component_builder\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\user\EntityOwnerTrait;

/**
 * Defines the Component Wrapper class.
 *
 * @ContentEntityType(
 *   id = "component_wrapper",
 *   label = @Translation("Component Wrapper"),
 *   label_collection = @Translation("Components"),
 *   label_singular = @Translation("Component"),
 *   label_plural = @Translation("Components"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Component Wrapper",
 *     plural = "@count Component Wrappers",
 *   ),
 *   bundle_label = @Translation("Component Wrapper type"),
 *   handlers = {
 *     "access" = "Drupal\entity\EntityAccessControlHandler",
 *     "query_access" = "Drupal\entity\QueryAccess\QueryAccessHandler",
 *     "permission_provider" = "Drupal\entity\EntityPermissionProvider",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\component_builder\ComponentWrapperListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "moderation" = "Drupal\content_moderation\Entity\Handler",
 *     "form" = {
 *       "default" = "Drupal\component_builder\Form\ComponentWrapperForm",
 *       "add" = "Drupal\component_builder\Form\ComponentWrapperForm",
 *       "edit" = "Drupal\component_builder\Form\ComponentWrapperForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm"
 *     },
 *     "inline_form" = "Drupal\component_builder\Form\ComponentWrapperInlineForm",
 *     "local_task_provider" = {
 *       "default" = "Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
 *     },
 *     "route_provider" = {
 *       "default" = "Drupal\entity\Routing\AdminHtmlRouteProvider",
 *       "delete-multiple" = "Drupal\entity\Routing\DeleteMultipleRouteProvider",
 *     },
 *   },
 *   admin_permission = "administer component_wrapper",
 *   permission_granularity = "bundle",
 *   translatable = TRUE,
 *   base_table = "component_wrapper",
 *   data_table = "component_wrapper_field_data",
 *   revision_table = "component_wrapper_revision",
 *   revision_data_table = "component_wrapper_field_revision",
 *   show_revision_ui = TRUE,
 *   entity_keys = {
 *     "id" = "component_wrapper_id",
 *     "revision" = "vid",
 *     "label" = "title",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid",
 *     "published" = "status",
 *     "owner" = "uid",
 *     "uid" = "uid",
 *   },
 *   links = {
 *     "canonical" = "/component-wrapper/{component_wrapper}",
 *     "add-form" = "/admin/structure/component-wrapper/add",
 *     "edit-form" = "/admin/structure/component-wrapper/{component_wrapper}/edit",
 *     "delete-form" = "/admin/structure/component-wrapper/{component_wrapper}/delete",
 *     "delete-multiple-form" = "/admin/structure/component-wrapper/delete",
 *     "collection" = "/admin/structure/component-wrappers",
 *   },
 *   field_ui_base_route = "entity.component_wrapper.settings",
 * )
 */
class ComponentWrapper extends ContentEntityBase implements ComponentWrapperInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;
  use EntityPublishedTrait;

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this->get('title')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setTitle($title) {
    $this->set('title', $title);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getTemplateMachineName() {
    $component_type = $this->get('component_type')->referencedEntities();
    if (is_array($component_type)) {
      $component_type = reset($component_type);
      $template_name = $component_type ? $component_type->get('name')->value : '';
      if ($template_name) {
        return preg_replace('@[^a-z0-9-]+@', '_', strtolower($template_name));
      }
    }
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getTemplateName() {
    $component_type = $this->get('component_type')->referencedEntities();
    if (is_array($component_type)) {
      $component_type = reset($component_type);
      return $component_type ? $component_type->get('name')->value : '';
    }
    return '';
  }

  /**
   * Get the field name of "items" field for current component type.
   *
   * @internal This is unstable API, do not use in contrib.
   */
  public function getItemFieldName(): string|NULL {
    $template_name = $this->getTemplateMachineName();
    return $template_name ? 'field_' . $template_name : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Component Title'))
      ->setTranslatable(TRUE)
      ->setDefaultValue('Untitled')
      ->setRequired(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -1,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['component_type'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Component Types'))
      ->setSetting('handler_settings', ['target_bundles' => ['taxonomy_term' => 'component_types']])
      ->setSetting('target_type', 'taxonomy_term')
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['display_title'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Display Title'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['display_header'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Display Header'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['display_footer'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Display Footer'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['display_image'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Display Images'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['display_in_region'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Display in region'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['custom_styles'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Custom Styles'))
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['field_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Images'))
      ->setDescription(t('The image of component wrapper.'))
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setTranslatable(TRUE)
      ->setSettings([
        'uri_scheme' => 'public',
        'file_directory' => '[date:custom:Y]-[date:custom:m]',
        'file_extensions' => 'png jpg jpeg',
      ])
      ->setDisplayOptions('form', [
        'type' => 'image_image',
        'weight' => 1,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'image',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_region'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Region'))
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', FALSE);

    $fields['field_weight_in_region'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Weight in region'))
      ->setDescription(t('Put component weight here. Please visit Structure > Block Layout to check other block weight'))
      ->setDisplayOptions('form', [
        'type' => 'number',
        'weight' => 3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', FALSE);

    $fields['field_header'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Header'))
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_left_column'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Left Column'))
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setSetting('target_type', 'component_wrapper')
      ->setDisplayOptions('form', [
        'type' => 'inline_entity_form_complex',
        'weight' => 5,
      ])
      ->setDisplayOptions('view', [
        'type' => 'entity_reference_entity_view',
        'label' => 'hidden',
        'settings' => [
          'view_mode' => 'full',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_middle_column'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Middle Column'))
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setSetting('target_type', 'component_wrapper')
      ->setDisplayOptions('form', [
        'type' => 'inline_entity_form_complex',
        'weight' => 5,
      ])
      ->setDisplayOptions('view', [
        'type' => 'entity_reference_entity_view',
        'label' => 'hidden',
        'settings' => [
          'view_mode' => 'full',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_right_column'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Right Column'))
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setSetting('target_type', 'component_wrapper')
      ->setDisplayOptions('form', [
        'type' => 'inline_entity_form_complex',
        'weight' => 5,
      ])
      ->setDisplayOptions('view', [
        'type' => 'entity_reference_entity_view',
        'label' => 'hidden',
        'settings' => [
          'view_mode' => 'full',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_footer'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Footer'))
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 9,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['field_properties'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Properties'))
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 25,
        'settings' => [
          'rows' => 4,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['field_display_mode'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Display mode'))
      ->setDescription(t('Display mode.'))
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['status']
      ->setLabel(t('Published'))
      ->setDisplayConfigurable('form', TRUE);

    $fields['uid']
      ->setLabel(t('Author'))
      ->setDescription(t('The entity author.'))
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setRevisionable(TRUE)
      ->setDescription(t('The time when the entity was created.'))
      ->setTranslatable(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setRevisionable(TRUE)
      ->setDescription(t('The time when the entity was last edited.'))
      ->setTranslatable(TRUE);

    return $fields;
  }

}
