<?php

namespace SEOAIC\shortcodes;

use SEOAIC\shortcodes\interfaces\ShortcodeInterface;

class PostThumbnail implements ShortcodeInterface
{
    private $attrs;

    public function __construct($attrs = [], $content = '')
    {
        $this->attrs = empty($attrs) ? [] : (is_array($attrs) ? $attrs : [$attrs]);
    }

    private function makeHTML(): string
    {
        $defaultSize = 'medium_large';
        $size = !empty($this->attrs['size']) ? $this->attrs['size'] : $defaultSize;
        $class = !empty($this->attrs['class']) ? $this->attrs['class'] : '';

        if (!in_array($size, self::getSizes())) {
            $size = $this->parseCustomSize($size);

            if (empty($size)) {
                $size = $defaultSize;
            }
        }

        return get_the_post_thumbnail(null, $size, [
            'class' => trim($class),
        ]);
    }

    public function html(): string
    {
        $html = $this->makeHTML();

        return $html;
    }

    public static function getSizes(): array
    {
        $registeredSizes = wp_get_registered_image_subsizes();
        $sizes = array_merge(array_keys($registeredSizes), ['full']);

        return array_unique($sizes);
    }

    public function parseCustomSize(string $str): array
    {
        preg_match('/^(\d{1,})x(\d{1,})$/', $str, $matches);

        return !empty($matches[1]) && !empty($matches[2])
            ? [$matches[1], $matches[2]]
            : [];
    }
}
