<?php

namespace OfficeBrain\Bundle\CoreBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Exception\ParseException;

class CoreController extends Controller
{
	/**
	 *
	 * @author Employee Id: 4074
	 *
	 * Desciption: Define member variables with thier default value
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function __construct()
	{
		$this->request = null;
		$this->tabcount = null;
		$this->cultureCode = null;
		$this->projectSetting = null;
		$this->orderManager = null;
		$this->wishListManager = null;
		$this->inlineViewProductMaxLimit =null;
		$this->compareProductManager = null;
		$this->quickQuoteManager = null;
		$this->requestQuoteManager = null;
	}

	/**
	 *
	 * @author Employee Id: 4074
	 *
	 * Desciption: Unset member variables
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function __destruct()
	{
		unset($this->request);
		unset($this->tabcount);
		unset($this->cultureCode);
		unset($this->projectSetting);
		unset($this->orderManager);
		unset($this->wishListManager);
		unset($this->inlineViewProductMaxLimit);
		unset($this->compareProductManager);
		unset($this->quickQuoteManager);
		unset($this->requestQuoteManager);
	}

	/**
	 *
	 * @author Employee Id: 4074
	 *
	 * Desciption: Create and initialize various required object and member variables
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->projectSetting = $this->request->get('project_setting');
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->tabcount = 0;
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->currencyConversionManager = $this->get('office_brain_currency_convesion_manager');
		$this->orderManager = $this->get('office_brain_order_manager');
		$this->wishListManager = $this->get('office_brain_wish_list_manager');
		$this->compareProductManager = $this->get('office_brain_compare_product_manager');
		$this->inlineViewProductMaxLimit = $this->projectSetting['configuration_rule']['transaction'];
		$this->quickQuoteManager = $this->quickQuoteManager = $this->get('office_brain_quick_quote_manager');
		$this->requestQuoteManager = $this->get ('office_brain_request_quote_manager'); 
	}

	/**
	 * @Route("/{_locale}/swtich-to-culture/{culture}", name="office_brain_corebundle_changeculture")
	 * @Method({"GET"})
	 * @Template()
	 */
	public function changeCultureAction($culture)
	{
		$this->initAction ();
		$request = $this->request;
		$referer = $request->headers->get('referer');
		$referer_url_para = parse_url($referer);

		$lastPath = $referer_url_para['path'];
		$referer = $referer_url_para['scheme'].'://'.$referer_url_para['host'].$referer_url_para['path'];

		$basePath = $request->getBaseUrl()?$request->getBaseUrl():( $referer_url_para['scheme'].'://'.$referer_url_para['host']);

		$lastPath = substr($referer, strpos($referer, $basePath));
		$lastPath = str_replace($basePath, '', $lastPath);

		if(!$lastPath) $lastPath = '/';

		$matcher = $this->get('router')->getMatcher();
		$parameters = $matcher->match($lastPath);

		$oldCulture = (array_key_exists('_locale', $parameters))?$parameters['_locale']:$this->cultureCode;
		$newCulture = $culture;
		$route = $parameters['_route'];

		if($route == 'office_brain_page_homepage') {
			$route = 'office_brain_page_homepage_view';
		}

		//echo $route; exit;
		
		$parameters['_locale'] = $culture;
		unset($parameters['_route']);
		unset($parameters['_controller']);
		unset($matcher);
		unset($request);
		unset($referer);

    if($route=='officebrain_product_bundle_product_detail')
    {
        $productDetailManager=$this->get('office_brain_product_detail_manager');
        if(!empty($productSlug=$productDetailManager->getProductSlugClutureWise($parameters['productSlug'],$oldCulture,$newCulture)))
        {
            $parameters['productSlug']=$productSlug;
        }
    }
    
		return $this->redirect($this->get('router')->generate($route, $parameters).(array_key_exists('query', $referer_url_para)?'?'.$referer_url_para['query']:''));
	}

	/**
	 * @author Employee Id: 5058
	 * Description : message yml to csv
	 *
	 * @Route("/admin/{_locale}/trans_csv",
	 * name="office_brain_corebundle_convertmessagefile",
	 * requirements={"records_per_page"="2|4|8|16|996", "page"="\d+"},
	 * defaults={"records_per_page"=2,"page"=1})
	 * )
	 *
	 * @Method("GET")
	 * @Template("OfficeBrainCoreBundle::trans.html.twig")
	 */
	public function transAction()
	{
		$this->initAction ();

		$dir =  $_SERVER['DOCUMENT_ROOT'];


		$destDir= $this->request->getBasePath();
		$destDir= $dir.$destDir.'/translations/';
		$dir =  $dir.'/product_web_client/';
		$dir =  '/var/www/product-web-client/';

		$rootHandle = opendir($dir);
		$rootFiles = scandir($dir);
		foreach ($rootFiles as $rootFiles)
		{
			if($rootFiles == 'src')
			{
				$srcFiles= $dir.'src/';
				$srcHandle = opendir($srcFiles);
				$srcFile = scandir($srcFiles);
				foreach ($srcFile as $srcFile)
				{
					if($srcFile == 'OfficeBrain')
					{
						$officeBrainBundle = $srcFiles.'OfficeBrain/';
						$officeBrainHandle = opendir($officeBrainBundle);
						$officeBrainFiles = scandir($officeBrainBundle);
						foreach ($officeBrainFiles as $officeBrainFiles)
						{
							if($officeBrainFiles == 'Bundle')
							{
								$bundle = $officeBrainBundle.'Bundle/';
								$bundleHandle = opendir($bundle);
								$bundleFiles = scandir($bundle);
								foreach ($bundleFiles as $bundleFiles=>$value)
								{
									$bundleFile = $bundle;
									if(!is_dir($value))
									{
										$destDirForBundle= $destDir."$value/";
										$bundleFile = $bundleFile."$value/";
										$bundleHandle = opendir($bundleFile);
										$bundleFiles = scandir($bundleFile);
										foreach ($bundleFiles as $bundleFiles)
										{
											if($bundleFiles == 'Resources')
											{
												$resourcesFile = $bundleFile."Resources/";
												$resourcesHandle = opendir($resourcesFile);
												$resourcesFiles = scandir($resourcesFile);
												foreach ($resourcesFiles as $resourcesFiles )
												{

													if($resourcesFiles == 'translations')
													{
														$translationFile = $resourcesFile."translations/";
														$translationHandle = opendir($translationFile);
														$translationFiles = scandir($translationFile);
														$this->compareMessagesFilesAction($translationFile);
														foreach($translationFiles as $translationFiles)
														{
															if (!file_exists($destDirForBundle)) {
																mkdir($destDirForBundle, 0777, true);
															}
															if($translationFiles == 'messages.en_us.yml')
															{
																$file = file_get_contents($translationFile.'messages.en_us.yml');
																$yaml = new Parser();
																$array = $yaml->parse($file);
																$fp = fopen($destDirForBundle.'messages.en_us.csv', "w");
																$this->writeArray($array,$fp);
																fclose($fp);
															}
															if($translationFiles == 'validators.en_us.yml')
															{
																$file = file_get_contents($translationFile.'validators.en_us.yml');
																$yaml = new Parser();
																$array = $yaml->parse($file);
																$fp = fopen($destDirForBundle.'validators.en_us.csv', "w");
																$this->writeArray($array,$fp);
																fclose($fp);
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		exit;
		return array();
	}

	public function writeArray($array1, $fp) {
		$prefix = null;
		if (! empty ( $array1 )) {
			if (count ( $array1 ) >= 1) {

				foreach ( $array1 as $key1 => $value1 ) {
					if (is_array ( $value1 )) {
						for($i = 0; $i < $this->tabcount; $i ++) {
							$prefix = $prefix . '"",';
						}
						fwrite ( $fp, $prefix . '"'.$key1.'"' . "\n" );
						$prefix = null;
						$this->tabcount ++;
						$this->writeArray ( $value1, $fp );
					} else {
						for($i = 0; $i < $this->tabcount; $i ++) {
							$prefix = $prefix . '"",';
						}
						fwrite ( $fp, $prefix .'"'. $key1.'"' . ',' . '"'.addslashes($value1) .'"'. "\n" );
						$prefix = null;
					}
				}
				if ($this->tabcount > 0) {
					$this->tabcount = $this->tabcount - 1;
				}
			}
		}
	}

	/**
	 * @author Employee Id: 5058
	 * Description : message ymls compare
	 *
	 * @Route("/admin/{_locale}/trans_cmp",
	 * name="office_brain_corebundle_comparemessagesfiles")
	 *
	 * @Method("GET")
	 * @Template("OfficeBrainCoreBundle::trans.html.twig")
	 */
	public function compareMessagesFilesAction($path)
	{
		echo $path."<br>";
		$this->initAction ();

		$rootDir=$path;

		if(file_exists($rootDir.'messages.en_us.yml') && file_exists($rootDir.'messages.fr_ca.yml'))
		{
			$file = file_get_contents($rootDir.'messages.en_us.yml');
			$destFile = file_get_contents($rootDir.'messages.fr_ca.yml');
			$yaml = new Parser();
			$array1 = $yaml->parse($file);
			$array2 = $yaml->parse($destFile);
			$result = $this->multi_diff($array1,$array2);
			echo "==================================================================================================<br>";
			echo $rootDir."<br>";
			$this->print_error($result);
			echo "==================================================================================================<br>";
		}
		if(!file_exists($rootDir.'messages.en_us.yml') || (!file_exists($rootDir.'messages.fr_ca.yml')))
		{
			echo "Please create FR_CA File";
		}
		return array();
	}

	public function multi_diff($arr1,$arr2){
		$result = array();
		foreach ($arr1 as $k=>$v){
			if(!isset($arr2[$k])){
				$result[$k] = $v;
			} else {
				if(is_array($v) && is_array($arr2[$k])){
					$diff = $this->multi_diff($v, $arr2[$k]);
					if(!empty($diff))
						$result[$k] = $diff;
				}
			}
		}
		return $result;
	}

	public function print_error($result)
	{
			foreach ($result as $k => $v)
			{

				if(is_array($v))
				{
					echo $k.": ";
					$this->print_error($v);
				}
				else
				{
					echo $k."<br/>";
				}
			}
	}



	/**
	 * @Route("/{_locale}/changeCityStateCountry", name="office_brain_corebundle_changecitystatecountry", options={"expose"=true})
	 * @Method({"POST"})
	 * @Template()
	 */
	public function changeCityStateCountryAction()
	{
	    $country = $this->getRequest()->get('countryId');
	    $state = $this->getRequest()->get('stateId');
        $callType = $this->getRequest()->get('call_type');
        $data = array();
        $master = $this->get('office_brain_core_manager');

        if($callType == 'country_code'){
        	$data['state_data'] = array();
        	$dataStateData=$master->getStateData($country);
	        // array override with keychange for json object issue (sorting issue)
	       	foreach ($dataStateData as $key=>$value) {
	       		$data['state_data']['_'.$key]=$value;
	       	}
        }
        if($callType == 'state_code'){
        	$data['city_data'] = array();
           	$dataCityData=$master->getCityData($state);
           	// array override with keychange for json object issue (sorting issue)
           	foreach ($dataCityData as $key=>$value) {
           		$data['city_data']['_'.$key]=$value;
           	}
        }

	    unset($country);
	    unset($state);
	    unset($callType);
	    unset($master);

	    return new JsonResponse($data);
	}
	
	
	/**
	 * @author Employee Id: 4203
	 *
	 * Description: OB eCommerce Product -  update all counter
	 *
	 * @Route("/{_locale}/recent-all-counter",
	 * 	name="office_brain_corebundle_allcounterlist",
	 *  options={"expose"=true}
	 * )
	 *
	 */
	public function allCounterListAction()
	{
		$this->initAction ();
		//echo "dfdfdf"; die;
		$this->responseArrayCompareProduct['total_record'] = $this->compareProductManager->getTotalCount();
		$this->responseArrayCompareProduct['record_set'] = $this->compareProductManager->getCompareProduct();
		
		$this->responseArrayCart['total_record'] = $this->orderManager->getTotalCount();
		$this->responseArrayCart['record_set'] = $this->orderManager->getMaxNoOfCart($this->inlineViewProductMaxLimit['shopping_cart']['inline_view']['option']['no_of_product']);
		
		$this->responseArrayWishList['record_set'] = $this->wishListManager->getMaxNoOfWishList($this->inlineViewProductMaxLimit['wish_list']['inline_view']['option']['no_of_product']);
		$this->responseArrayWishList['total_record'] = $this->wishListManager->getTotalCount();
		
		//$this->responseArrayQuickQuote['record_set'] = $this->quickQuoteManager->getMaxNoOfQuickQuote($this->inlineViewProductMaxLimit['quick_quote']['inline_view']['option']['no_of_product']);
		//$this->responseArrayQuickQuote['total_product'] = $this->quickQuoteManager->getTotalCount();
		
		//$this->responseArrayRequestQuote['total_record'] = $this->requestQuoteManager->getTotalCount();
		//$this->responseArrayRequestQuote['record_set'] = $this->requestQuoteManager->getMaxNoOfQuote ($this->inlineViewProductMaxLimit['request_quote']['inline_view']['option']['no_of_product']);
		
		$compareHtml = $this->get('twig')->render("OfficeBrainCompareProductBundle:CompareProduct:recentCompareProductList.html.twig",$this->responseArrayCompareProduct);
		
		$cartHtml = $this->get('twig')->render("OfficeBrainOrderBundle:Order:recentCartList.html.twig",$this->responseArrayCart);
		
		$wishListHtml = $this->get('twig')->render("OfficeBrainWishListBundle:WishList:recentWishList.html.twig",$this->responseArrayWishList);
		
		//$quickQuoteHtml = $this->get('twig')->render("OfficeBrainQuickQuoteBundle:QuickQuote:recentQuickQuoteList.html.twig",$this->responseArrayQuickQuote);
		
		//$requestQuoteHtml = $this->get('twig')->render("OfficeBrainRequestQuoteBundle:RequestQuote:recentRequestQuoteList.html.twig",$this->responseArrayRequestQuote);
		return new JsonResponse(array('compare_product'=>$compareHtml,'compare_count'=>$this->responseArrayCompareProduct['total_record']
		,'wish_list'=>$wishListHtml,'wish_list_count'=>$this->responseArrayWishList['total_record'],'cart'=>$cartHtml,'cart_count'=>$this->responseArrayCart['total_record']));
		//return new JsonResponse(array('compare_product'=>$compareHtml,'wish_list'=>$wishListHtml,'quick_quote'=>$quickQuoteHtml,'cart'=>$cartHtml,'request_quote'=>$requestQuoteHtml));
	}

}
