<?php

namespace smusatov\bzb2u\Render;

use smusatov\bzb2u\Job;
use smusatov\bzb2u\Render;

class Text extends Render
{
    protected array $lines = [];

    public function addLine(string $text, ?string $font = NULL): void
    {
        if($text === '') {
            throw new \Exception('Text in line not be empty');
        }

        $this->lines[] = [
          'font' => $font,
          'text' => $text,
        ];
    }

    protected function renderLine(array $line, int $width, int $height): \Imagick
    {
        $draw = new \ImagickDraw();
        $draw->setGravity(\Imagick::GRAVITY_CENTER);
        $draw->setStrokeAntialias(false);
        $draw->setTextAntialias(false);
        $draw->setFillColor(new \ImagickPixel('#000000'));
        $draw->setTextUnderColor(new \ImagickPixel('#ffffff'));

        if(!is_null($line['font'])) {
            $draw->setFont($line['font']);
        }

        $im = new \Imagick();
        $im->setGravity(\Imagick::GRAVITY_CENTER);
        $im->setType(\Imagick::IMGTYPE_BILEVEL);
        $im->setAntiAlias(false);
        $im->setFormat('png');
        $im->setCompression(\Imagick::COMPRESSION_NO);
        $im->setBackgroundColor(new \ImagickPixel('#ffffff'));

        $fontSize = 7;
        do {
            $fontSize++;
            $draw->setFontSize($fontSize);
            $metrics = $im->queryFontMetrics($draw, $line['text'], false);

        } while($metrics['textWidth'] <= $width && $metrics['textHeight'] <= $height);
        $draw->setFontSize($fontSize - 1);

        $im->newImage($width, $height, new \ImagickPixel('#ffffff'), 'png');
        $im->setImageGravity(\Imagick::GRAVITY_CENTER);
        $im->annotateImage($draw, 0, 0, 0, $line['text']);

        return $im;
    }

    public function render(): Job
    {
        $im = new \Imagick();
        $im->setGravity(\Imagick::GRAVITY_NORTHEAST);
        $im->setType(\Imagick::IMGTYPE_BILEVEL);
        $im->setAntiAlias(false);
        $im->setFormat('png');
        $im->setCompression(\Imagick::COMPRESSION_NO);
        $im->setBackgroundColor(new \ImagickPixel('#ffffff'));
        $im->newImage($this->label->getWidthDots(), $this->label->getHeightDots(), new \ImagickPixel('#ffffff'), 'png');

        $widthLine = $this->label->getWidthDots() - 12;
        $heightLine = floor(($this->label->getHeightDots() - 12) / count($this->lines));
        $offsetTop = 3;
        foreach($this->lines as $line) {
            $line = $this->renderLine($line, $widthLine, $heightLine);
            $im->compositeImage($line, \Imagick::COMPOSITE_DEFAULT, floor(($widthLine - $line->getImageWidth()) / 2) + 6, floor(($heightLine - $line->getImageHeight()) / 2) + $offsetTop - 1);

            $offsetTop += $heightLine;
        }

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

}
