<?php

namespace KupShop\AdminBundle\Util;

use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;

readonly class SystemImageUtils
{
    public function __construct(private PathFinder $pathFinder, private LanguageContext $languageContext)
    {
    }

    public function getImageSrc(string $filename, string $suffix): string
    {
        $imageSrc = $this->getSystemImagesDir()."{$this->languageContext->getActiveId()}/{$filename}.{$suffix}";
        if (!file_exists($imageSrc)) {
            $imageSrc = $this->getSystemImagesDir()."{$filename}.{$suffix}";
            if (!file_exists($imageSrc)) {
                return '';
            }
        }

        return $imageSrc;
    }

    public function getSystemImagePlaceholderPath(): string
    {
        $imagePlaceholderPath = $this->getImageSrc('image-placeholder', 'png');

        if (!file_exists($imagePlaceholderPath)) {
            $imagePlaceholderPath = 'common/static/images/image-placeholder.png';
        }

        return $imagePlaceholderPath;
    }

    private function getSystemImagesDir(): string
    {
        return $this->pathFinder->getDataDir().'system-images/';
    }

    public function getBinaryFileResponse(string $filename, string $suffix): BinaryFileResponse
    {
        if (findModule(\Modules::PROXY_CACHE)) {
            $response = new BinaryFileResponse($this->getImageSrc($filename, $suffix));
            $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
            $response->setPublic()->setMaxAge(3600 * 24); // One day

            return $response;
        }

        return new BinaryFileResponse($this->getImageSrc($filename, $suffix));
    }

    public function getImageSrcRemote(string $filename, string $suffix): ?string
    {
        $addr = Config::get()->getFromArray('Addr');

        $imageSrc = $addr['full_original'].$this->getSystemImagesDir()."{$this->languageContext->getActiveId()}/{$filename}.{$suffix}";
        if ($this->remoteFileExists($imageSrc)) {
            return $imageSrc;
        }

        $imageSrc = $addr['full_original'].$this->getSystemImagesDir()."{$filename}.{$suffix}";
        if ($this->remoteFileExists($imageSrc)) {
            return $imageSrc;
        }

        return null;
    }

    private function remoteFileExists(string $url): bool
    {
        $context = stream_context_create(['http' => ['method' => 'HEAD']]);
        if ($headers = get_headers($url, context: $context) ?? null) {
            if (preg_match("/^HTTP.+\s(\d\d\d)\s/", $headers[0], $match)) {
                $statusCode = $match[1];

                return $statusCode < 400;
            }
        }

        return false;
    }
}
