<?php

namespace OfficeBrain\CustomBundle\PageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use OfficeBrain\Bundle\PageBundle\Controller\HomePageController as BaseHomePageController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class HomePageController extends BaseHomePageController
{
	
	public function __construct()
	{
		$this->statsh_cache_wrapper = RedisCacheService::create();
	}

	public function __destruct()
	{
		unset($this->statsh_cache_wrapper);
	}
	
	/**
	 * @Route("/operation/clear_cache",
	 * 	name="office_brain_page_clear_cache",
	 *  options={"expose"=true}
	 * )
	 *
	 */
	public function clearCacheAction(Request $request)
	{
		$appPath = $this->get('kernel')->getRootDir();
		$shPath = $appPath."/..";
		$phpPath = "/usr/bin/php";
		$webPath = $appPath."/../web";
		$identifier = $request->get('identifier');
		$identifierUpper = strtoupper($identifier);
		
		$commandResponse = shell_exec('sh '.$shPath.'/clear_cache.sh '.$appPath.' '.$shPath.' '.$phpPath.' '.$webPath.' '.$identifier.' '.$identifierUpper.' 2>&1; echo $?');
		
		$commandResponse = "<pre>$commandResponse</pre>";
		return new response($commandResponse);
	}
	
	/**
	 * @Route("/operation/remove_expired_price",
	 * 	name="office_brain_page_remove_expired_price",
	 *  options={"expose"=true}
	 * )
	 *
	 */
	public function removeExpiredPriceAction(Request $request)
	{
		$appPath = $this->get('kernel')->getRootDir();
		$shPath = $appPath."/..";
		$phpPath = "/usr/bin/php";
		$webPath = $appPath."/../web";
		$identifier = $request->get('identifier');
		$identifierUpper = strtoupper($identifier);
		
		$commandResponse = shell_exec('sh '.$shPath.'/remove_expired_price.sh '.$appPath.' '.$shPath.' '.$phpPath.' '.$webPath.' '.$identifier.' '.$identifierUpper.' 2>&1; echo $?');
		
		$commandResponse = "<pre>$commandResponse</pre>";
		return new response($commandResponse);
	}
	
	/**
	 * @Route("/operation/remove_expired_products_live",
	 * 	name="office_brain_page_remove_expired_products_live",
	 *  options={"expose"=true}
	 * )
	 *
	 */
	public function removeExpiredProductLiveAction()
	{
		$commandResponse = shell_exec('sh remove_expired_price_live.sh 2>&1; echo $?');
		
		$commandResponse = "<pre>$commandResponse</pre>";
		return new response($commandResponse);
	}

	/**
	 * @Route("/{slug}",
	 * 	name="office_brain_page_html_design_view",
	 * )
	 *
	 * @Template("OfficeBrainCustomBundlePageBundle:HomePage:designHtml.html.twig")
	 */
	public function htmlDesignAction($slug)
	{
		$this->initAction();
		
		if($slug == 'en_us')
		{
			return $this->redirect($this->generateUrl('office_brain_page_homepage'));
		}
		//RedirectMatch 301 (?i)/ColorJet /en_us/search?tag_id%5B%5D=colorjet
		if(strtolower($slug) == strtolower('colorjet'))
		{
			return $this->redirect($this->generateUrl('office_brain_search_bundle_search', array('_locale' => 'en_us','tag_id[]' => 'colorjet')));
		}
		//RedirectMatch 301 (?i)/Newfor18 /en_us/search?tag_id[]=what-s-new
		if(strtolower($slug) == strtolower('newfor18'))
		{
			return $this->redirect($this->generateUrl('office_brain_search_bundle_search', array('_locale' => 'en_us','tag_id[]' => 'what-s-new')));
		}
		//RedirectMatch 301 (?i)/IPUExclusive /en_us/search?main_filter=keyword&search_query=IPU+Exclusive
		if(strtolower($slug) == strtolower('IPUExclusive'))
		{
			return $this->redirect($this->generateUrl('office_brain_search_bundle_search', array('_locale' => 'en_us','main_filter' => 'keyword','search_query' => 'IPU Exclusive')));
		}
		//RedirectMatch 301 (?i)/HaloExclusive /en_us/search?main_filter=keyword&search_query=Halo+Exclusive
		if(strtolower($slug) == strtolower('HaloExclusive'))
		{
			return $this->redirect($this->generateUrl('office_brain_search_bundle_search', array('_locale' => 'en_us','main_filter' => 'keyword','search_query' => 'Halo Exclusive')));
		}
		//RedirectMatch 301 (?i)/AIAExclusive /en_us/search?main_filter=keyword&search_query=AIA+Exclusive
		if(strtolower($slug) == strtolower('AIAExclusive'))
		{
			return $this->redirect($this->generateUrl('office_brain_search_bundle_search', array('_locale' => 'en_us','main_filter' => 'keyword','search_query' => 'AIA Exclusive')));
		}
		//RedirectMatch 301 (?i)/DSP /en_us/flyer/featured-self-promotions
		if(strtolower($slug) == strtolower('DSP'))
		{
			return $this->redirect($this->generateUrl('office_brain_flyerbundle_flyer_supplierflyer', array('_locale' => 'en_us','slug' => 'featured-self-promotions')));
		}
		//RedirectMatch 301 (?i)/DSP /en_us/flyer/featured-self-promotions
		if(strtolower($slug) == strtolower('Unscripted'))
		{
			return $this->redirect($this->generateUrl('office_brain_page_html_design_view', array('slug' => 'simplicity','source' => 'unscripted')));
		}

		$this->basePath = $this->container->getParameter('base_path');
		$this->baseUrl  = $this->container->getParameter('base_url');
		$format = 'html';
		if (file_exists(strtolower($this->basePath .'/htmls_dev/'. $slug.'.'.$format))) {
			//return new BinaryFileResponse($this->baseUrl .'/htmls/'. $slug.'.'.$format);
			return new Response(file_get_contents(strtolower($this->baseUrl .'/htmls_dev/'. $slug.'.'.$format)));
		}
		return;
	}

	/**
	 * @Route("/",
	 * 	name="office_brain_page_homepage",
	 *  options={"expose"=true}
	 * )
	 * @Route("/{_locale}",
	 * 	name="office_brain_page_homepage_view",
	 *  options={"expose"=true}
	 * )
	 *
	 * @Template("OfficeBrainPageBundle:HomePage:index.html.twig")
	 */
	public function indexAction()
	{
		$projectSetting = $this->getRequest()->get('project_setting');
		$locale = $projectSetting['locale_language'];
		$data=array();
		// -----------------------------------------------------------------------
        $cacheSiteKey = array($locale,$this->container->getParameter('kernel.environment'));
		$this->moduleCachePrefix='__HomePageBrandList__:';
		$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
		$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
		if($cacheData){
			$data['brandList']= json_decode($cacheData,true);
		}else{
			$arrLocale=explode("_", $locale);
			$brands = $this->get("officebrain_brand_api_manager")->getList($arrLocale[0]);
			if(!empty($cacheKey))
			{
				RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,json_encode($brands));
			}
			$data['brandList']= $brands;
		}
		return $data;
	}

	/**
	 * @Route("/{_locale}/get-product-tag-block-data",
	 * 	name="office_brain_page_homepage_producttag_data",
	 * )
	 *
	 */
	public function getProductTagBlockAction($slug= null){
		
		//$this->initAction();
		
		$projectSetting = $this->getRequest()->get('project_setting');
		$locale=$projectSetting['locale_language'];
		$cookies = $this->getRequest()->cookies;

		$arrLocale=explode("_", $locale);
		$data=array();

		$countryId = $this->container->getParameter('country')[$arrLocale[1]]['id'];
		$this->productTagManager = $this->get('office_brain_custombundle_product_tag_manager');

		$this->moduleCachePrefix='__ProductTagManagement__';

		$userType = 'guest';
		if ($this->userId > 0) {
			$userType = 'register';
		}
		if ($cookies->has('CUSTOM_SITE_CULTURE'))
		{
			$changeCountry = $cookies->get('CUSTOM_SITE_CULTURE');
			if($changeCountry != $locale){
				$locale = $changeCountry;
			}
			unset($changeCountry);
		}
		$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$userType,$locale);

		$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
		if($cacheData){
			return $cacheData;
		}

		$data['tag_icon_url'] = $this->getParameter('private_tag.icon_url').'featured-icon/';
		$data['newproduct_private_tag_products'] = $this->productTagManager->getPrivateTagByCategoryId($this->container->getParameter('private_tag_category')['newproducts_tag_id'],true);
		$data['promotional_private_tag_products'] = $this->productTagManager->getPrivateTagByCategoryId($this->container->getParameter('private_tag_category')['promotional_tag_id'], true);

		$response = $this->render('OfficeBrainCustomBundlePageBundle:HomePage:productTag.html.twig', $data);

		if(!empty($cacheKey))
		{
			RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
		}

		return $response;
	}
}
