<?php

namespace Velis\Image\Processor\Decorator;

use Imagick;
use Velis\Filesystem\FilesystemInterface;

final class RotateDecorator extends ImageProcessorDecorator
{
    public function __construct(
        protected FilesystemInterface $filesystem,
        protected readonly ?int $angle = null, // If null, it will be determined from EXIF data
    ) {
        parent::__construct($filesystem);
    }

    public function process(string $key): void
    {
        $img = new Imagick();
        $img->readImageBlob($this->filesystem->read($key));

        $angle = null;

        if ($this->angle) {
            $angle = $this->angle;
        } else {
            $exifData = $img->getImageProperties('exif:*');
            if (!empty($exifData) && $exifData['exif:Orientation'] && $exifData['exif:Orientation'] != 1) {
                switch ($exifData['exif:Orientation']) {
                    case 3:
                        $angle = 180;
                        break;
                    case 6:
                        $angle = 90;
                        break;
                    case 8:
                        $angle = -90;
                        break;
                }
            }
        }

        if ($angle) {
            $img->rotateImage('#00000000', $angle);

            $this->filesystem->write($key, $img->getImageBlob());
        }
    }
}
