<?php

namespace Doom\Image;

use Doom\Picture\Palette;
use Doom\Picture\Picture;
use Intervention\Image\ImageManager;
use Intervention\Image\Interfaces\ImageInterface;

final class PictureRenderer
{
    public function __construct(
        private ImageManager $manager,
        private Palette $palette,
    )
    {
    }

    public function render(Picture $picture): ImageInterface
    {
        $image = $this->manager->createImage($picture->width, $picture->height);
        $image->fill('rgba(0,0,0,0)');

        $colorCache = ['transparent' => 'rgba(0, 0, 0, 0)'];

        foreach ($picture->posts as $x => $columnPosts) {
            if (!\is_int($x) || $x < 0 || $x >= $picture->width) {
                continue;
            }

            foreach ($columnPosts as $post) {
                $y = $post['y'];
                $pixels = $post['pixels'];

                foreach ($pixels as $offset => $pixelIndex) {
                    $pixelY = $y + $offset;
                    if ($pixelY < 0 || $pixelY >= $picture->height) {
                        continue;
                    }

                    $paletteIndex = $pixelIndex & 0xFF;
                    if (!isset($colorCache[$paletteIndex])) {
                        [$r, $g, $b] = $this->palette->colorAt($paletteIndex);
                        $colorCache[$paletteIndex] = sprintf('rgb(%d, %d, %d)', $r, $g, $b);
                    }

                    $image->drawPixel($x, $pixelY, $colorCache[$paletteIndex]);
                }
            }
        }

        return $image;
    }
}
