<?php

namespace smusatov\bzb2u;

class Job
{
    protected Label $label;
    protected array $data;
    protected int $count = 1;

    public function __construct(Label $label)
    {
        $this->label = $label;
        $this->data = array_fill(1, $this->label->getHeightDots(), array_fill(1, $this->label->getWidthDots(), false));
    }

    public function getLabel(): Label
    {
        return $this->label;
    }

    public function getCount(): int
    {
        return $this->count;
    }

    public function setCount(int $count): void
    {
        $this->count = min(99, max(1, $count));
    }

    public function getPixel(int $x, int $y): bool
    {
        if(!isset($this->data[$y][$x])) {
            throw new \Exception('Out of range');
        }

        return $this->data[$y][$x];
    }

    public function setPixel(int $x, int $y, bool $value = true): void
    {
        if(!isset($this->data[$y][$x])) {
            throw new \Exception('Out of range');
        }

        $this->data[$y][$x] = $value;
    }

    public function getLines(): \Generator
    {
        foreach($this->data as $line) {
            $line = array_map(fn($bit) => $bit ? 1 : 0, $line);

            yield $line;
        }
    }

    public function getPreview()
    {
        $draw = new \ImagickDraw();
        $draw->setFillColor(new \ImagickPixel('#000000'));

        foreach($this->data as $y => $row){
            foreach($row as $x => $value){
                if(!$value) {
                    continue;
                }

                $draw->point($x-1, $y-1);
            }
        }

        $im = new \Imagick();
        $im->newImage($this->label->getWidthDots(), $this->label->getHeightDots(),new \ImagickPixel('#ffffff'));
        $im->setImageFormat('png');
        $im->drawImage($draw);

        return $im->getImageBlob();
    }
}
