<?php

declare(strict_types=1);

namespace Drupal\farm_comment;

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\entity\BundleFieldDefinition;

/**
 * Helper methods for farm_comment.
 */
class FarmCommentHelper {

  /**
   * Generate a standard comment base field definition.
   *
   * @param string $entity_type
   *   The entity type.
   *
   * @return \Drupal\Core\Field\BaseFieldDefinition
   *   Returns a comment base field definition.
   */
  public static function commentBaseFieldDefinition(string $entity_type) {

    // Create a new comment field definition.
    // We use BundleFieldDefinition instead of BaseFieldDefinition to force
    // Drupal to create a separate database table for this field. Otherwise, if
    // it is added to the base table then the comment field default value is
    // always 0 (CommentItemInterface::HIDDEN) instead of 2
    // (CommentItemInterface::OPEN), because the
    // Drupal\comment\Plugin\Field\FieldType\CommentItem::schema() default is 0.
    $field = BundleFieldDefinition::create('comment');

    // Set the field label.
    $field->setLabel(t('Comments'));

    // We assume that the comment type matches the entity type.
    $field->setSetting('comment_type', $entity_type);

    // Disable previews.
    $field->setSetting('preview', 0);

    // A default value must be set for comment fields.
    // Enable comments on entities by default.
    $default_value = [
      [
        'status' => CommentItemInterface::OPEN,
        'cid' => 0,
        'last_comment_timestamp' => 0,
        'last_comment_name' => '',
        'last_comment_uid' => 0,
        'comment_count' => 0,
      ],
    ];
    $field->setDefaultValue($default_value);

    // Build form display settings.
    $field->setDisplayOptions('form', [
      'type' => 'comment_default',
      'weight' => 450,
    ]);

    // Build view display settings.
    // Display comments on the bottom of entity view displays by default, with
    // the field label above them.
    $field->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'comment_default',
      'weight' => 1000,
    ]);

    return $field;
  }

}
