<?php
namespace DevOwl\HeadlessContentBlocker\plugins;

use DevOwl\FastHtmlTag\finder\match\AbstractMatch;
use DevOwl\FastHtmlTag\finder\match\TagAttributeMatch;
use DevOwl\HeadlessContentBlocker\AbstractPlugin;
use DevOwl\HeadlessContentBlocker\BlockedResult;
use DevOwl\HeadlessContentBlocker\Constants;
use DevOwl\HeadlessContentBlocker\matcher\AbstractMatcher;

/**
 * Append a calculated unique key of the tag to the tag.
 */
class CalculateUniqueKeys extends AbstractPlugin {
    /**
     * See `AbstractPlugin`. We need to use this hook so we have all original attributes available.
     *
     * @param BlockedResult $result
     * @param AbstractMatcher $matcher
     * @param AbstractMatch $match
     */
    public function blockedMatch($result, $matcher, $match) {
        // Prepare ID keys ordered by priority
        $idKeys = [Constants::HTML_ATTRIBUTE_VISUAL_ID . '-overwrite'];

        if ($match instanceof TagAttributeMatch && filter_var($match->getLink(), FILTER_VALIDATE_URL)) {
            $idKeys[] = $match->getLinkAttribute();
        }

        $idKeys[] = 'id';

        $key = $match->calculateUniqueKey($idKeys, [
            ['key' => 'blockerId', 'value' => $result->getFirstBlocked()->getBlockerId()],
        ]);

        if ($key !== null) {
            $match->setAttribute(Constants::HTML_ATTRIBUTE_VISUAL_ID, $key);
        }
    }
}
