<?php

namespace IZON\Thumber\Image;


use IZON\Filesystem\FilesystemSourceInterface;
use IZON\IO\Image;
use IZON\IO\RasterImageInterface;
use IZON\Thumber\Exceptions\ImageNotFoundException;
use IZON\Thumber\Exceptions\ImageSizeIsNotSetException;
use IZON\Thumber\ImageConfiguration\IImageConfiguration;


/**
 * ImageUrlBuilder
 * @author Aleš Kopecký <kopecky@izon.cz>
 */
class ImageURLBuilder implements IImageURLBuilder {

    /**
     * @var FilesystemSourceInterface
     */
    protected $filesystemSource;


    /**
     *
     * @var string
     */
    protected $path = '';

    /**
     * ImageUrlBuilder constructor.
     * @param FilesystemSourceInterface $filesystemSource
     */
    public function __construct(FilesystemSourceInterface $filesystemSource) {
        $this->filesystemSource = $filesystemSource;
    }

    /**
     * Sets path to image lazy controller.
     * @param string $path
     */
    public function setPath(string $path) {
        $this->path = $path;
    }

    /**
     * Create URL to controller with params.
     * @param IImageConfiguration $config
     * @return string
     */
    public function buildURL(IImageConfiguration $config): string {
        $params = [
            'image' => $config->getImage()->getFileUID(),
            'width' => $config->getWidth(),
            'height' => $config->getHeight(),
            'quality' => $config->getQuality(),
            'type' => $config->getType(),
            'name' => $config->getName(),
            'cache' => $config->isCache(),
            'format' => $config->getFormat()
        ];
        if(!empty($config->getOrigin())) {
            $params['origin'] = $config->getOrigin();
        }
        if($config->hasCrop()) {
            if($config->getCropPoint() instanceof IImagePoint) {
                $params['cropPointX'] = $config->getCropPoint()->getX();
                $params['cropPointY'] = $config->getCropPoint()->getY();
            }
            if($config->getCropSize() instanceof IImageSize) {
                $params['cropSizeWidth'] = $config->getCropSize()->getWidth();
                $params['cropSizeHeight'] = $config->getCropSize()->getHeight();
            }
        }
        $url = "/". $this->path .'?'. http_build_query($params);
        return $url;
    }

    /**
     * creates image from parameters stored in url
     * @param array $params
     * @return RasterImageInterface
     */
    public function getImage(array $params): RasterImageInterface {

        $filesystem = $this->filesystemSource->getFilesystem($params['origin']);
        if(!$filesystem->has($params['image'])) {
            throw new ImageNotFoundException("Image '{$params['image']}' not found in origin {$params['origin']}.");
        }
        $imageIO = $filesystem->getFile($params['image']);
        return $imageIO;
    }
}
