<?php

namespace IZON\Thumber\Web\Controllers;

use IZON\MVC\Controller;
use IZON\MVC\Exceptions\PageNotFoundException;
use IZON\MVC\HttpRequest;
use IZON\MVC\ModelAndView;
use IZON\Thumber\Exceptions\ImageNotFoundException;
use IZON\Thumber\Exceptions\ImageSizeIsNotSetException;
use IZON\Thumber\Image\ImageURLBuilder;
use IZON\Thumber\Services\ThumbnailServiceInterface;
use IZON\Thumber\Web\Utils\WebPImageUtils;

/**
 * Controller which handles lazy creating images in cache.
 */
class ImageLazyController implements Controller {

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

    /**
     *
     * @param ThumbnailServiceInterface $thumberService
     */
    public function __construct(ThumbnailServiceInterface $thumberService) {
        $this->thumbnailService = $thumberService;
    }

    /**
     * Based on parameters in URL creates demanded image in cache and redirects to it.
     * @param HttpRequest $request
     * @return ModelAndView
     */
    public function execute(HttpRequest $request) {
        if( WebPImageUtils::hasWebPSupport(getallheaders()) ) { // get all headers needed to work properly
            // Do something for WebP users
            $this->thumbnailService->setFormat('webp');
        }
        try {
            $image = $this->thumbnailService->getImageURLBuiler()->getImage($request->getParameters());
            $imageConfiguration = $this->thumbnailService->createThumbnailImageConfiguration($image, $request->getParameters());
        } catch(ImageNotFoundException $ex) {
            throw new PageNotFoundException("Image not found", 1, $ex);
        } catch(ImageSizeIsNotSetException $ex) {
            throw new PageNotFoundException("Image size not set", 2, $ex);
        }
        $filePath = $this->thumbnailService->getThumbnailURL($imageConfiguration);
        if(!$imageConfiguration->isCache()) {
            $finfo = new \finfo(FILEINFO_MIME_TYPE);
            header('Content-Type: '.$finfo->buffer($filePath));
            echo $filePath;
            die;
        }
        return ModelAndView::createURLRedirect($filePath);
    }
}
