<?php
declare(strict_types=1);

namespace WP_AUX\Services;

use AuxCF\Entities\Field\Enum\DateFieldFormatEnum;
use WP_AUX\Entities\AuxCF\PageFields\Story\StorySourceAuthorFieldEntity;
use WP_AUX\Entities\AuxCF\PageFields\Story\StorySourceOrganizationFieldEntity;
use WP_AUX\Entities\AuxCF\PageFields\Story\StorySourceOriginalDateFieldEntity;

class StoryService
{
  public static function authorshipGroupsString($source, ...$groupNames) {
    $authorshipBlocks = [];

    $allGroupsSingle = true;
    foreach ($groupNames as $groupName) {
      $groupItems = [];

      if (empty($source[$groupName])) {
        continue;
      }

      foreach ($source[$groupName] as $sourceItem) {
        $groupItems[] = $sourceItem->name;
      }

      if (count($groupItems) !== 1) {
        $allGroupsSingle = false;
      }

      $lastItem = false;

      if (count($groupItems) > 1) {
        $lastItem = array_pop($groupItems);
      }

      $listString = join(', ', $groupItems);

      if (!empty($lastItem)) {
        $listString .= ' and ' . $lastItem;
      }

      $authorshipBlocks[] = '<span class="author">' . $listString . '</span>';
    }

    $separator = $allGroupsSingle ? ', ' : ' | ';

    return join($separator, $authorshipBlocks);
  }

  /**
   * If a post has had a signifigant change, editors add the original publish date
   * in the 'Original Publication Date' ACF field and update the native WP publish
   * date to the new date.
   */
  public static function getOriginalDate(int|\WP_Post|null $post = 0, string|\UnitEnum|null $format = null): string
  {
    $source = get_field('aux_story_source', $post);

    $dateValue = @$source[StorySourceOriginalDateFieldEntity::$name];

    if (empty($dateValue)) {
      $dateValue = get_post($post)->post_date;
    }

    if (empty($dateValue)) {
      return '';
    }

    if (empty($format)) {
      $format = DateFieldFormatEnum::ApAbbr;
    }

    if ($format instanceof \UnitEnum) {
      if (method_exists($format, 'formatDate')) {
        return $format->formatDate($dateValue);
      }

      $format = $format->value;
    }

    $date = new \DateTime($dateValue);

    return (string) $date->format($format);
  }

  public static function getBylineAuthors(int|\WP_Post|null $post = 0): string
  {
    $source = get_field('aux_story_source', $post);

    $by = self::authorshipGroupsString(
      $source,
      StorySourceAuthorFieldEntity::$name,
      StorySourceOrganizationFieldEntity::$name
    );

    return HtmlService::formattedValue(
      $by,
      'By %s'
    );
  }

  public static function searchResultSubheader(): string
  {
    return self::getOriginalDate() . ' &bull; ' . PostService::pageReadTime();
  }

  public static function prepareHooks(): void
  {
    add_action('init', function() {
      CustomPostTypesService::registerCustomPostType(
        'news',
        'News',
        'News',
        null,
        ['category', 'post_tag'],
        'dashicons-welcome-widgets-menus',
        0
      );
      CustomPostTypesService::registerPermalinkStructure('news', 'date');

      CustomTagsService::registerCustomTags(
        'story-author',
        ['news'],
        'Authors',
        'Author',
        true,
        false,
        false
      );

      CustomTagsService::registerCustomTags(
        'story-organization',
        ['news'],
        'Organizations',
        'Organization',
        true,
        false,
        false
      );
    }, 1);
  }
}
