<?php

declare(strict_types=1);

namespace Intervention\Image\Drivers\Gd\Modifiers;

use Intervention\Image\Exceptions\ColorDecoderException;
use Intervention\Image\Exceptions\ModifierException;
use Intervention\Image\Exceptions\StateException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
use Intervention\Image\Modifiers\DrawRectangleModifier as GenericDrawRectangleModifier;

class DrawRectangleModifier extends GenericDrawRectangleModifier implements SpecializedInterface
{
    /**
     * {@inheritdoc}
     *
     * @see ModifierInterface::apply()
     *
     * @throws ModifierException
     * @throws StateException
     * @throws ColorDecoderException
     */
    public function apply(ImageInterface $image): ImageInterface
    {
        $position = $this->drawable->position();

        foreach ($image as $frame) {
            // draw background
            if ($this->drawable->hasBackgroundColor()) {
                imagealphablending($frame->native(), true);
                imagesetthickness($frame->native(), 0);
                imagefilledrectangle(
                    $frame->native(),
                    $position->x(),
                    $position->y(),
                    $position->x() + $this->drawable->width(),
                    $position->y() + $this->drawable->height(),
                    $this->driver()->colorProcessor($image)->export(
                        $this->backgroundColor()
                    )
                );
            }

            // draw border
            if ($this->drawable->hasBorder()) {
                imagealphablending($frame->native(), true);
                imagesetthickness($frame->native(), $this->drawable->borderSize());
                imagerectangle(
                    $frame->native(),
                    $position->x(),
                    $position->y(),
                    $position->x() + $this->drawable->width(),
                    $position->y() + $this->drawable->height(),
                    $this->driver()->colorProcessor($image)->export(
                        $this->borderColor()
                    )
                );
            }
        }

        return $image;
    }
}
