<?php
/**
 * @package Hafenstudios\Wellenbrecher
 */

namespace Hafenstudios\Wellenbrecher\Rules;

use Hafenstudios\Wellenbrecher\Engine\Context;
use Hafenstudios\Wellenbrecher\Engine\RuleResult;
use Hafenstudios\Wellenbrecher\Support\Text;

defined( 'ABSPATH' ) || exit;

/**
 * Link-Zeichen-Anteil ueber 30 Prozent: der Text besteht ueberwiegend
 * aus URLs.
 */
class LinkRatioRule extends AbstractRule {

	public const ID             = 'link_ratio';
	public const DEFAULT_POINTS = 20;

	public const MAX_RATIO = 0.30;

	public function __construct( int $points = self::DEFAULT_POINTS ) {
		parent::__construct( $points );
	}

	public function id(): string {
		return self::ID;
	}

	public function stage(): int {
		return 2;
	}

	public function evaluate( Context $context ): RuleResult {
		$content = trim( $context->field( 'content' ) );
		$total   = mb_strlen( $content );
		if ( 0 === $total ) {
			return $this->miss();
		}

		$link_chars = 0;
		foreach ( Text::urls( $content ) as $url ) {
			$link_chars += mb_strlen( $url );
		}
		if ( 0 === $link_chars ) {
			return $this->miss();
		}

		return ( $link_chars / $total ) > self::MAX_RATIO ? $this->hit() : $this->miss();
	}
}
