<?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\ThumbnailService;

/**
 * Controller which handles lazy creating images in cache.
 */
class ImageLazyController implements Controller {
    
    /**
     *
     * @var ThumbnailService 
     */
    protected $thumberService;

    /**
     * 
     * @param ThumbnailService $thumberService
     */
    public function __construct(ThumbnailService $thumberService) {
        $this->thumberService = $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) {
        try {
            $imageConfiguration = ImageUrlBuilder::fromArray($request->getParameters());
        } catch(ImageNotFoundException $ex) {
            throw new PageNotFoundException("Not found Image", 1, $ex);
        } catch(ImageSizeIsNotSetException $ex) {
            throw new PageNotFoundException("Not set size of image", 2, $ex);
        }
        $filePath = $this->thumberService->createThumbnailPath($imageConfiguration);
        return ModelAndView::createURLRedirect('/'.$filePath);        
    }
}
