<?php

namespace OfficeBrain\Bundle\CacheBundle\Listener;
	
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Kernel;

/**
	 * Request listener for serving response from cache
	 * 
	 * Response listener for caching response to cache
	 *
	 * @author OfficeBrain 4074 <info@officebrain.com>
	 *
	 */
	class ClientSideCacheListener
	{
		const RFC_JSON_STD = 'application/json';
		const IE9_JSON_STD = 'text/json';
		const IE9_USER_AGENT = 'MSIE 9.0';
		
	    public function __construct()
	    {
	    	$this->request = null;
	    	$this->response = null;
	    }

	    public function __destruct()
	    {
	    	unset($this->request);
	    	unset($this->response);
	    }

	    /**
	     * Request listener for serving response from cache
	     *
	     * @param GetResponseEvent $event
	     */
	    public function onKernelResponseSetCacheHeaderForJs($event)
	    {
	    	$this->init($event);      
	        $this->setJsonHeaderForIE();
	        $this->setCacheHeaderForJs();
		}
		
		/**
		 * Private function to initialize the cache related variables
		 *
		 * @param $event
		 *
		 * @author OfficeBrain 4074 <info@officebrain.com>
		 */
		
		private function init($event)
		{
			$this->request = $event->getRequest();
			$this->response = $event->getResponse();
		}
		
		private function setJsonHeaderForIE() 
		{
			if ($this->response->headers->has('Content-Type') && $this->request->headers->has('user-agent')) {
				if ($this->isIE9Request($this->response->headers->get('Content-Type'), $this->request->headers->get('user-agent'))) {
					$this->response->headers->set('Content-Type', self::IE9_JSON_STD);
				}
			}
		}
		
		/**
		 * [
		 * @param string $contentType
		 * @param string $userAgent
		 *
		 * @return boolean true if requerst is done from ie 9 and response required is json
		 */
		private function isIE9Request($contentType,$userAgent)
		{
		
			return preg_match('/'.str_replace('/', '\/', self::RFC_JSON_STD).'/', $contentType)!=0 && preg_match('/'.self::IE9_USER_AGENT.'/', $userAgent)!=0;
		}
		
		private function setCacheHeaderForJs()
		{
			$routeName = $this->request->get('_route');
			
			if($routeName == 'bazinga_jstranslation_js' || $routeName == 'fos_js_routing_js') {
				$this->response->headers->removeCacheControlDirective('no-cache');
				$this->response->setCache(array(
						'max_age'=> 100000000,
						's_maxage'=> 10000000,
						'public'=> true,
						'private' => false,
				));
			}
			
			unset($routeName);
		}
	}
