<?php

namespace dominion\file;

use Yii;
use Imagine\Image\Palette\RGB;
use Imagine\Image\ManipulatorInterface;
use Imagine\Image\Point;
use Imagine\Image\ImageInterface;


class Image extends \yii\imagine\Image
{

    public static function thumbnail($image, $width, $height, $mode = ManipulatorInterface::THUMBNAIL_OUTBOUND)
    {
        $img = self::ensureImageInterfaceInstance($image);
        /** @var BoxInterface $sourceBox */
        $sourceBox = $img->getSize();
        $thumbnailBox = static::getThumbnailBox($sourceBox, $width, $height);

        $img = $img->thumbnail($thumbnailBox, $mode);

        $size = $img->getSize();

        $palette = new RGB();
        $color = $palette->color(static::$thumbnailBackgroundColor, static::$thumbnailBackgroundAlpha);

        // create empty image to preserve aspect ratio of thumbnail
        $thumb = static::getImagine()->create($thumbnailBox, $color);

        // calculate points
        $startX = 0;
        $startY = 0;
        if ($size->getWidth() < $width) {
            $startX = ceil(($width - $size->getWidth()) / 2);
        }
        if ($size->getHeight() < $height) {
            $startY = ceil(($height - $size->getHeight()) / 2);
        }

        $thumb->paste($img, new Point($startX, $startY));

        return $thumb;
    }

    public static function thumbnailFileTemplate($image, $width, $height, $fileTemplate, $mode = ImageInterface::THUMBNAIL_INSET)
    {
        $newWidth = $width - $fileTemplate['border_right'] - $fileTemplate['border_left'];
        $newHeight = $height - $fileTemplate['border_top'] - $fileTemplate['border_bottom'];

        $img = self::ensureImageInterfaceInstance($image);
        /** @var BoxInterface $sourceBox */
        $sourceBox = $img->getSize();
        $thumbnailBox = static::getThumbnailBox($sourceBox, $newWidth, $newHeight);

        $img = $img->thumbnail($thumbnailBox, $mode);
        $size = $img->getSize();

        // calculate points
        $startX = 0;
        $startY = 0;
        if ($size->getWidth() < $newWidth) {
            $startX = ceil(($newWidth - $size->getWidth()) / 2);
        }
        if ($size->getHeight() < $newHeight) {
            $startY = ceil(($newHeight - $size->getHeight()) / 2);
        }
        $startX += $fileTemplate['border_right'];
        $startY += $fileTemplate['border_top'];

        // create empty image to preserve aspect ratio of thumbnail
        $thumb = static::getImagine()->open($fileTemplate['filePatch']);
        $thumb->paste($img, new Point($startX, $startY));

        return $thumb;
    }

}