<?php

namespace Drupal\nodehive_core\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\link\LinkItemInterface;
use Drupal\nodehive_core\SpaceInterface;

/**
 * Defines the space entity class.
 *
 * @ContentEntityType(
 *   id = "nodehive_space",
 *   label = @Translation("Space"),
 *   label_collection = @Translation("Spaces"),
 *   label_singular = @Translation("space"),
 *   label_plural = @Translation("spaces"),
 *   label_count = @PluralTranslation(
 *     singular = "@count spaces",
 *     plural = "@count spaces",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\nodehive_core\SpaceListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\nodehive_core\SpaceAccessControlHandler",
 *     "query_access" = "\Drupal\entity\QueryAccess\QueryAccessHandler",
 *     "permission_provider" = "\Drupal\entity\EntityPermissionProvider",
 *     "form" = {
 *       "add" = "Drupal\nodehive_core\Form\SpaceForm",
 *       "edit" = "Drupal\nodehive_core\Form\SpaceForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     }
 *   },
 *   base_table = "nodehive_space",
 *   admin_permission = "administer nodehive space",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "collection" = "/admin/content/space",
 *     "add-form" = "/space/add",
 *     "canonical" = "/space/{nodehive_space}",
 *     "edit-form" = "/space/{nodehive_space}/edit",
 *     "delete-form" = "/space/{nodehive_space}/delete",
 *   },
 * )
 */
class Space extends ContentEntityBase implements SpaceInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);

    if (!$update) {
      foreach (["nodehive-editor", "nodehive-admin"] as $menu_id) {
        // Create a menu item in Switch Space menu.
        $menu = $this->entityTypeManager()->getStorage('menu')
          ->load($menu_id);

        if (!$menu) {
          continue;
        }

        // Find switch space.
        $switch_space_menu_link = $this->entityTypeManager()->getStorage("menu_link_content")
          ->loadByProperties([
            'title' => "Spaces",
            'menu_name' => $menu_id,
          ]);
        $switch_space_menu_link = end($switch_space_menu_link);

        if (!$switch_space_menu_link) {
          continue;
        }

        $menu_link = $this->entityTypeManager()->getStorage("menu_link_content")
          ->loadByProperties([
            'title' => $this->label(),
            'menu_name' => $menu_id,
            'parent' => "menu_link_content:" . $switch_space_menu_link->uuid(),
          ]);

        if (!$menu_link) {
          $menu_link = $this->entityTypeManager()->getStorage("menu_link_content")
            ->create([
              'title' => $this->label(),
              'link' => ['uri' => 'internal:/space/' . $this->id()],
              'menu_name' => $menu_id,
              'parent' => "menu_link_content:" . $switch_space_menu_link->uuid(),
              'expanded' => TRUE,
            ]);
          $menu_link->save();
        }
      }

      return;
    }

    if ($update) {
      foreach (["nodehive-editor", "nodehive-admin"] as $menu_id) {
        $link = \Drupal::entityTypeManager()->getStorage("menu_link_content")
          ->loadByProperties([
            'title' => $this->original->label(),
            'link' => [
              'uri' => "internal:/space/" . $this->id(),
            ],
            'menu_name' => $menu_id,
          ]);

        if (!$link || count($link) >= 2) {
          continue;
        }

        /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */
        $link = end($link);
        $link->set('title', $this->label());
        $link->save();
      }
    }

  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);

    foreach ($entities as $entity) {
      foreach (["nodehive-editor", "nodehive-admin"] as $menu_id) {
        // Create a menu item in Switch Space menu.
        $menu = \Drupal::entityTypeManager()->getStorage('menu')
          ->load($menu_id);

        if (!$menu) {
          continue;
        }

        // Find switch space.
        $switch_space_menu_link = \Drupal::entityTypeManager()->getStorage("menu_link_content")
          ->loadByProperties([
            'title' => "Spaces",
            'menu_name' => $menu_id,
            'parent' => $menu_id,
          ]);
        $switch_space_menu_link = end($switch_space_menu_link);

        if (!$switch_space_menu_link) {
          continue;
        }

        $menu_link = \Drupal::entityTypeManager()->getStorage("menu_link_content")
          ->loadByProperties([
            'title' => $entity->label(),
            'menu_name' => $menu_id,
            'parent' => "menu_link_content:" . $switch_space_menu_link->uuid(),
          ]);

        foreach ($menu_link as $link) {
          $link->delete();
        }
      }

      return;
    }
  }

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

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['machine_name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Machine name'))
      ->setDescription(t('A unique machine-readable name for this space. Can be used as a consistent identifier across environments.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['thumbnail'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Thumbnail'))
      ->setDescription(t('Thumbnail of the space.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'image',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'image_image',
        'weight' => -3,
        'settings' => [
          'preview_image_style' => 'thumbnail',
          'progress_indicator' => 'throbber',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['menu'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Content'))
      ->setDescription(t('The reference content.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'menu')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'region' => 'hidden',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['content_types'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Content Types'))
      ->setDescription(t('Allowed content types. Leave empty to allow all.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'node_type')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'options_buttons',
        'weight' => -2,
        'settings' => [],
      ])
      ->setDisplayConfigurable('form', TRUE);

    // @todo We switched to 'users', update the field name.
    $fields['editors'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Users'))
      ->setDescription(t('Users that have access to space content.'))
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => -1,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ]);

    $fields['space_url'] = BaseFieldDefinition::create('link')
      ->setLabel(t('Url'))
      ->setDescription(t('The space urls.'))
      ->setRequired(TRUE)
      ->setSettings([
        'link_type' => LinkItemInterface::LINK_EXTERNAL,
        'title' => DRUPAL_DISABLED,
      ])
      ->setDisplayOptions('form', [
        'type' => 'link_default',
        'weight' => 0,
      ])
      ->setCardinality(1)
      ->setDisplayConfigurable('form', TRUE);

    $fields['space_type'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Space Type'))
      ->setDescription(t('Type of space.'))
      ->setSetting('allowed_values_function', 'nodehive_core_space_type_allowed_values')
      ->setRequired(TRUE)
      ->setCardinality(1)
      ->setDisplayOptions(
        'form',
        [
          'type' => 'select',
          'weight' => 0,
        ],
      )
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', FALSE);

    $fields['frontpage_node'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Frontpage Node'))
      ->setDescription(t('Node used for the frontpage.'))
      ->setSetting('target_type', 'node')
      ->setRequired(FALSE)
      ->setSetting('handler', 'default')
      ->setCardinality(1)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 0,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ]);

    $fields['frontpage_login_url'] = BaseFieldDefinition::create('link')
      ->setLabel(t('Frontpage Login Url'))
      ->setDescription(t('The login url for the frontpage.'))
      ->setRequired(FALSE)
      ->setSettings([
        'link_type' => LinkItemInterface::LINK_EXTERNAL,
        'title' => DRUPAL_DISABLED,
      ])
      ->setDisplayOptions('form', [
        'type' => 'link_default',
        'weight' => 0,
      ])
      ->setCardinality(1)
      ->setDisplayConfigurable('form', TRUE);

    $fields['tags'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Tags'))
      ->setDescription(t('Space tags.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'taxonomy_term')
      ->setSetting('handler', 'default')
      ->setSetting('handler_settings', [
        'target_bundles' => [
          'nodehive_space_tags' => 'nodehive_space_tags',
        ],
        'auto_create' => TRUE,
        'auto_create_bundle' => 'nodehive_space_tags',
      ])
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 0,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ]);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Status'))
      ->setDefaultValue(TRUE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => 0,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['git_repository'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Git Repository'))
      ->setDescription(t('The Git repository URL for this space.'))
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['hosting_provider'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Frontend Hosting Provider'))
      ->setDescription(t('The hosting provider for the frontend.'))
      ->setSetting('allowed_values', [
        'vercel' => 'Vercel',
        'netlify' => 'Netlify',
        'netnode_cloud' => 'NETNODE.cloud',
        'other' => 'Other',
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time that the space was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the space was last edited.'));

    $fields['apikey'] = BaseFieldDefinition::create('string')
      ->setLabel(t('API Key'))
      ->setSetting('max_length', 255)
      ->setReadOnly(TRUE);

    return $fields;
  }

}
