<?php

declare(strict_types=1);

namespace App\Domain\QrCode\Pattern;

use App\Domain\QrCode\ValueObject\Position;

class FinderPattern implements PatternInterface
{
    public function __construct(
        private readonly Position $position
    ) {
    }

    public function apply(array &$matrix, int $size): void
    {
        $row = $this->position->getRow();
        $col = $this->position->getColumn();

        // 7x7 Finder Pattern
        for ($i = 0; $i < 7; $i++) {
            for ($j = 0; $j < 7; $j++) {
                // Äußerer Rand oder inneres Quadrat
                $isBlack = ($i === 0 || $i === 6 || $j === 0 || $j === 6) ||
                           ($i >= 2 && $i <= 4 && $j >= 2 && $j <= 4);

                $position = new Position($row + $i, $col + $j);
                if ($position->isWithinBounds($size)) {
                    $matrix[$row + $i][$col + $j] = $isBlack;
                }
            }
        }

        // Weißer Separator um das Finder Pattern
        $this->applySeparator($matrix, $size);
    }

    private function applySeparator(array &$matrix, int $size): void
    {
        $row = $this->position->getRow();
        $col = $this->position->getColumn();

        // Horizontaler Separator unten
        for ($j = 0; $j < 8; $j++) {
            $position = new Position($row + 7, $col + $j);
            if ($position->isWithinBounds($size)) {
                $matrix[$row + 7][$col + $j] = false;
            }
        }

        // Vertikaler Separator rechts
        for ($i = 0; $i < 8; $i++) {
            $position = new Position($row + $i, $col + 7);
            if ($position->isWithinBounds($size)) {
                $matrix[$row + $i][$col + 7] = false;
            }
        }
    }

    public static function createAll(int $size): array
    {
        return [
            new self(new Position(0, 0)),                // Oben links
            new self(new Position(0, $size - 7)),        // Oben rechts
            new self(new Position($size - 7, 0))         // Unten links
        ];
    }
}
