<?php

namespace Bastion\Handlers;

use Openguru\OpenCartFramework\Http\Request;
use Openguru\OpenCartFramework\ImageTool\ImageFactory;
use Symfony\Component\HttpFoundation\Response;

class ImageHandler
{
    private ImageFactory $image;

    public function __construct(ImageFactory $image)
    {
        $this->image = $image;
    }

    public function getImage(Request $request): Response
    {
        $path = $request->query->get('path');
        [$width, $height] = $this->parseSize($request->query->get('size'));

        return $this->image
            ->make($path)
            ->resize($width, $height)
            ->response();
    }

    private function parseSize(?string $size = null): array
    {
        if (! $size) {
            return [null, null];
        }

        $sizes = explode('x', $size);

        return array_map(static fn($value) => is_numeric($value) ? (int) $value : null, $sizes);
    }
}
