<?php

namespace IZON\Thumber;

use Exception;
use IZON\IO\Image;
use IZON\IO\RasterImage;
use IZON\IO\RasterImageInterface;
use IZON\Thumber\Exceptions\ThumbnailException;
use IZON\Thumber\Services\ThumbnailServiceInterface;

/**
 * Slouzi k vygenerovani a vraceni nahledu obrazku
 */
class Thumbnailer {

    const AVAILABLE_AS = '_thumbnailer';

    /**
     * Default image quality
     */
    const DEFAULT_QUALITY = 90;

    /**
     * supported alignments used for example of application of watermatks
     */
    const SUPPORTED_ALIGNMENTS = [
        'top-left', // (default)
        'top',
        'top-right',
        'left',
        'center',
        'right',
        'bottom-left',
        'bottom',
        'bottom-right',
    ];

    /**
     * @var ThumbnailServiceInterface
     */
    protected $thumberService;

    function __construct(ThumbnailServiceInterface $thumberService) {
        $this->thumberService = $thumberService;
    }

    /**
     * returns url where to get resized image
     * @param RasterImageInterface|string|null $sourceImage source image or parh to image on default file system or NoImage if null provided
     * @param array $parameters parametry pro resizovani <br>width = cislo, <br>heigth = cislo, <br>type type = ["contain": vleze se do, "cover": da se pokryt] default je contain, <br>quality = number, default = 90 <br>napr. ["width" => 1234], ["width" => 1234, "type" => "contain"]
     * @return string
     */
    public function getThumbnailURL($sourceImage, array $parameters = []) {
        try {
            if(!$sourceImage instanceof RasterImageInterface) { // raster image was not provided to function
                if( $sourceImage !== null
                    && $this->thumberService->hasDefaultFileSystemImage($sourceImage) ) { // file exists in default fule system
                    // use file from default file system
                    $sourceImage = $this->thumberService->getDefaultFileSystemImage($sourceImage);
                } else {
                    $sourceImage = $this->thumberService->getNoImage();
                }
            }
            $imageConfig = $this->thumberService->createThumbnailImageConfiguration($sourceImage, $parameters);
            $url = $this->thumberService->getThumbnailURL($imageConfig);
            return $url;
        } catch(ThumbnailException $exception) {
            $imageConfig = $this->thumberService->createThumbnailImageConfiguration($this->thumberService->getNoImage(), $parameters);
            $url = $this->thumberService->getThumbnailURL($imageConfig);
            return $url;
        }
    }
}
