<?php

namespace IZON\Thumber\Web\Interceptors;

use IZON\MVC\HttpRequest;
use IZON\MVC\Interceptors\Interceptor;
use IZON\MVC\ModelAndView;
use IZON\Thumber\Services\ThumbnailService;
use IZON\Thumber\Thumber;
use IZON\UserAgent\Exceptions\UserAgentParseException;
use IZON\UserAgent\UserAgentParser;

/**
 * nacita informace o ga
 */
class ThumberInterceptor implements Interceptor {
    /**
     *
     * @var ThumbnailService 
     */
    protected $thumberService;

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

    public function afterCompletion(HttpRequest $request, $exception) {
        
    }

    public function preHandle(HttpRequest $request) {
        if((isset($_SERVER['HTTP_ACCEPT']) === true) && (strstr($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false)) {
            // Do something for WebP users
            $this->thumberService->setFormat('webp');
        }
        if( isset($_SERVER['HTTP_USER_AGENT']) ) { // we have
            // try to detect agents with WebP support for lossy, lossless & alpha
            // support list taken fom https://developers.google.com/speed/webp/faq
            try {
                $userAgent = UserAgentParser::parse(getallheaders());
                if(
                    $userAgent->isBrowser('Chrome', '>=', 23) && $userAgent->isType('desktop')  // Google Chrome (desktop) 23+
                    || $userAgent->isBrowser('Chrome', '>=', 25) && $userAgent->isType('mobile') // Google Chrome for Android version 25+
                    || $userAgent->isBrowser('Edge', '>=', 18) // Microsoft Edge 18+
                    || $userAgent->isBrowser('Firefox', '>=', 65) // Firefox 65+
                    || $userAgent->isBrowser('Opera', '>=', '12.10') // Opera 12.10+\
                    || $userAgent->isBrowser('Pale Moon', '>=', 26) // Pale Moon 26+
                ) {
                    // Do something for WebP users
                    $this->thumberService->setFormat('webp');
                }
            } catch(UserAgentParseException $exception) {
                // let the exception slide
            }
        }
    }

    public function postHandle(HttpRequest $request, ModelAndView $model) {
        // adds information about gallery
        $model->putParameter(Thumber::AVAILABLE_AS, $this->thumberService->getThumber());
        return $model;
    }

}
