<?php

namespace Doom\Image;

use Doom\Picture\Picture;
use Intervention\Image\Interfaces\ImageInterface;
use InvalidArgumentException;
use RuntimeException;

final class TextureRenderer
{
    protected ImageInterface $image;

    public function __construct(
        private Renderer $renderer,
        private PictureRenderer $pictureRenderer,
        int $width, int $height
    ) {
        if ($width <= 0 || $height <= 0) {
            throw new InvalidArgumentException('Texture dimensions must be greater than zero.');
        }

        $this->image = $renderer->create($width, $height);
    }

    public function blit(Picture|string $source, int $x = 0, int $y = 0): self
    {
        if (\is_string($source) && !is_file($source)) {
            throw new RuntimeException("Unable to blit texture source file: {$source}");
        }

        $image = $source instanceof Picture ? $this->pictureRenderer->render($source) : $source;
        $this->image->insert($image, $x, $y);

        return $this;
    }

    public function image() : ImageInterface
    {
        return $this->image;
    }
}
