<?php
namespace GemBoards\Classes\Mention;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use WP_Post;
use WP_REST_Request;
class Task extends  Base\Mention {
	protected string $type = 'task';

	public static function init() : void {
		$post_type = GEMBOARDS_PLUGIN_SLUG . '_task';
		add_filter( "rest_prepare_{$post_type}", function ( $response, $post, $request ) {
			$ins                                   = new static( '', $post->ID );
			$response->data['content']['rendered'] = $ins->rendered();

			if ( ! empty( $post->post_content ) && empty( $response->data['content']['rendered'] ) ) {
				$original                              = apply_filters( 'the_content', $post->post_content );
				$ins                                   = new static( $original, $post->ID );
				$response->data['content']['rendered'] = $ins->rendered( true );
			}
			return $response;
		}, 10, 3);

		add_filter( "rest_after_insert_{$post_type}", function ( WP_Post $post, WP_REST_Request $request, bool $creating ) {
			$original = apply_filters( 'the_content', $post->post_content );
			$ins      = new static( $original, $post->ID );
			$ins->rendered( true );
		}, 10, 3);
	}

	public function rendered( bool $update = false ): ?string {
		if ( $update ) {
			update_post_meta( $this->id, $this->type . '_rendered', $this->get_rendered_content() );
		}
		return get_post_meta( $this->id, $this->type . '_rendered', true );
	}

	protected function get_mentioned() : ?array {
		$mentioned = get_post_meta( $this->id, $this->key, true);
		return empty( $mentioned ) ? [] : $mentioned;
	}

	protected function update_mentioned( array $usernames ) : void {
		update_post_meta( $this->id, $this->key, $usernames );
	}
}
