<?php

namespace smusatov\bzb2u\Render;

use Imagick;
use ImagickPixel;
use smusatov\bzb2u\Job;
use smusatov\bzb2u\Label;
use smusatov\bzb2u\Render;

class Image extends Render
{
    protected \Imagick $image;
    protected bool $fitImage = false;

    public function __construct(Label $label, string $file)
    {
        parent::__construct($label);

        $this->image = new Imagick();
        $this->image->readImage($file);
        $this->image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
    }

    public function setFillImage()
    {
        $this->fitImage = false;
    }

    public function setFitImage()
    {
        $this->fitImage = true;
    }

    public function render(): Job
    {
        $im = new Imagick();
        $im->setGravity(Imagick::GRAVITY_CENTER);
        $im->newImage($this->label->getWidthDots(), $this->label->getHeightDots(), new ImagickPixel('#ffffff'));
        $im->setImageGravity(Imagick::GRAVITY_CENTER);

        if($this->label->getWidthDots() < $this->image->getImageWidth() || $this->label->getHeightDots() < $this->image->getImageHeight()) {
            if($this->fitImage) {
                $this->image->resizeImage($this->label->getWidthDots() - 12, $this->label->getHeightDots() - 12, Imagick::FILTER_LANCZOS2, 0.1, true);
            } else {
                if($this->label->getWidthDots() / $this->label->getHeightDots() > $this->image->getImageWidth() / $this->image->getImageHeight()) {
                    $width = $this->image->getImageWidth();
                    $height = $this->label->getHeightDots() * $width / $this->label->getWidthDots();
                } else {
                    $height = $this->image->getImageHeight();
                    $width = $this->label->getWidthDots() * $height / $this->label->getHeightDots();
                }
                $this->image->cropImage($width, $height, abs($width - $this->image->getImageWidth()) / 2, abs($height - $this->image->getImageHeight()) / 2);
                $this->image->resizeImage($this->label->getWidthDots(), $this->label->getHeightDots(), Imagick::FILTER_LANCZOS2, 0.1, true);
            }
        }

        $im->compositeImage($this->image, Imagick::COMPOSITE_DEFAULT, floor(abs($this->label->getWidthDots() - $this->image->getImageWidth()) / 2), floor(abs($this->label->getHeightDots() - $this->image->getImageHeight()) / 2));

        $im->setImageType(Imagick::IMGTYPE_BILEVEL);
        $im->setFormat('png');

        return $this->makeJob($im);
    }

}
