<?php
namespace GemBoards\Classes\Mention;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use WP_Comment;
use WP_REST_Request;
class Comment extends  Base\Mention {

	protected string $type = 'task_comment';

	public static function init() : void {
		add_filter( 'rest_prepare_comment', function ( $response, $comment, $request ) {
			$post_id          = $comment->comment_post_ID;
			$target_post_type = get_post_type($post_id);

			$post_type = GEMBOARDS_PLUGIN_SLUG . '_task';
			if ( $post_type === $target_post_type ) {
				$content = $response->data['content']['rendered'] ?? '';
				$ins     = new static( $content, $comment->comment_ID );

				$response->data['content']['rendered'] = $ins->rendered();
				$response->data['content']['raw']      = $content;

				if ( ! empty( $comment->comment_content ) &&
					empty( $response->data['content']['rendered'] )
				) {
					$ins                                   = new static( $comment->comment_content, $comment->comment_ID );
					$response->data['content']['rendered'] = $ins->rendered( true );
				}
			}
			return $response;
		}, 10, 3);

		add_filter( 'rest_after_insert_comment', function ( WP_Comment $comment, WP_REST_Request $request, bool $creating ) {
			$post_id          = $comment->comment_post_ID;
			$target_post_type = get_post_type( $post_id );
			$post_type        = GEMBOARDS_PLUGIN_SLUG . '_task';
			if ( $post_type === $target_post_type ) {
				$ins = new static( $comment->comment_content, $comment->comment_ID );
				$ins->rendered( true );
			}
		}, 10, 3);
	}

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

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

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