<?php

namespace OfficeBrain\Bundle\AccessManagementBundle\Listener;

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContext;
use OfficeBrain\Bundle\AccessManagementBundle\Manager\Service\AccessManagementService;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use OfficeBrain\Bundle\CoreBundle\Cache\Redis;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
 * Request listener for serving response from cache.
 *
 * Response listener for caching response to cache
 *
 * @author OfficeBrain 4074 <info@officebrain.com>
 */
class AccessConfigurationListener
{
	private $serviceGroupId;
	private $router;
    public $statsh_cache_wrapper;

    public function __construct(Kernel $kernel, EntityManager $entityManager, SecurityContext $context, $router)
    {
        $this->kernel = $kernel;
        $this->entityManager = $entityManager;
        $this->serviceContainer = $kernel->getContainer();
        $this->sessionManager = null;
        $this->context = $context;
        $this->router = $router;
        RedisCacheService::$serviceContainer = $kernel->getContainer();
    }

    public function __destruct()
    {
        unset($this->kernel);
        unset($this->request);
        unset($this->userId);
        unset($this->sessionManager);
        unset($this->entityManager);
        unset($this->context);
        unset($this->statsh_cache_wrapper);
    }

    private function OthereAccessAndConfigurationRules($event=null)
    {
        // 1. Find instance bnased on hostname
        //$this->findInstance($event);

        // 2. load configuration rules based on instance

        // 3. detedt user
        // 4. load access rules based on instance and user
    }

    /**
     * Request listener for serving response from cache.
     *
     * @param GetResponseEvent $event
     *
     * @author OfficeBrain 4074 <info@officebrain.com>
     */
    public function onKernelRequestPrepareAccessAndConfigurationRules($event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            $this->request=$event->getRequest();
            $masterRequest=$this->serviceContainer->get('request_stack')->getMasterRequest();
            if (!empty($masterRequest) && $masterRequest instanceof Request) {
                $rule_array['project_setting']=$masterRequest->get('project_setting');
                $rule_array['project_user_setting']=$masterRequest->get('project_user_setting');
                $this->request->attributes->add($rule_array);
            }
            return;
        }
        $this->init($event);
        $this->OthereAccessAndConfigurationRules($event);
    }

    /**
     * Private function to initialize configuration and access for cli request
     *
     * @param CLI_REQUEST $cliRequest
     *
     * @author OfficeBrain 4646 <jgamit@officebrain.com>
     */
    public function PrepareAccessAndConfigurationRulesForCli($cliRequest)
    {
        $this->init(null, $cliRequest);
        $this->OthereAccessAndConfigurationRules();
    }
    /**
     * Public function to initialize configuration and access for exception request
     *
     * @param  $event
     *
     * @author OfficeBrain 4505 <kparmar@officebrain.com>
     */
    public function PrepareAccessAndConfigurationRulesForException($event)
    {
    	$this->init($event,null);
    	$this->OthereAccessAndConfigurationRules();
    }
    /**
     * Private function to initialize the related variables.
     *
     * @param $event
     * @param $cliRequest
     *
     * @author OfficeBrain 4074 <info@officebrain.com>
     */
    private function init($event, $cliRequest=null)
    {
    	$this->event = $event;
    	$this->clientRequest = $cliRequest;
        if (!$this->clientRequest) {
            $this->request = $this->event->getRequest();
            $this->isClientRequest = false;
        } else {
            $this->request = $this->clientRequest;
            $this->isClientRequest = true;
        }


        $this->host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && $_SERVER['HTTP_X_FORWARDED_HOST']!='')?$_SERVER['HTTP_X_FORWARDED_HOST']:$this->request->getHost();

        /* Find the instance and Set default Configuration Data */
        $this->findInstanceAndSetdefaultConfigurationData();
        
        /* set instance master data */
        $this->setInstanceMasterData();
        
        // set current user data
        $this->setCurrentUserData();
        
        /* set access rule data */
        $this->setAccessRuleData();
        
        /* set Configuration rule data */
        $this->setConfigurationRuleData();
        
        /* set instance theme meta data */
        $this->setInstanceThemeMetaData();

        //echo '<pre>';print_r($this->request->get('project_setting'));echo '</pre>';exit;
        
    }

    /**
     * @author Employee Id: 4273
     * Description : Find the instance and Set default Configuration Data
     *
     * */
    public function findInstanceAndSetdefaultConfigurationData()
    {
    	$instanceData = $this->findInstance($this->event);
      
    	$instanceId = !empty($instanceData['instance_id'])?$instanceData['instance_id']:$this->serviceContainer->getParameter('default_main_instance_id'); // Set This instance Id in user provider also
    	$instanceType = !empty($instanceData['instance_type'])?$instanceData['instance_type']:$this->serviceContainer->getParameter('default_main_instance_type'); // Set This instance Id in user provider also
    	$siteOwnerId = !empty($instanceData['site_owner_id']) ? $instanceData['site_owner_id']: 1;
    	$instanceFrontendTheme = $instanceTheme = !empty($instanceData['instance_theme'])?$instanceData['instance_theme']:$this->serviceContainer->getParameter('default_main_instance_theme'); // Set This instance Id in user provider also
    	$isMainInstance = !empty($instanceData['is_main_instance']) ? $instanceData['is_main_instance']: false;
    	
    	$cultureId = !empty($instanceData['culture_id'])?$instanceData['culture_id']:'1';
    	$cultureCode = !empty($instanceData['culture_code'])?$instanceData['culture_code']:'en_us';
    	$currencyCode = !empty($instanceData['currency_code'])?$instanceData['currency_code']:'$';
    	$currencyName = !empty($instanceData['currency_name'])?$instanceData['currency_name']:'$';
    	$priceInDecimal = !empty($instanceData['price_in_decimal'])?$instanceData['price_in_decimal']:2;

    	/*if (!empty($instanceData['allowed_culture']) && in_array($this->request->getLocale(), $instanceData['allowed_culture']) || $this->request->getLocale() == 'en_ca') {
    		$localLanguage = $this->request->getLocale();
    	} else {
    		header('Location: '.$this->serviceContainer->getParameter('base_url'));
    		die;
    	}*/

    	$localLanguage = (!empty($instanceData['allowed_culture']) && in_array($this->request->getLocale(), $instanceData['allowed_culture']))?$this->request->getLocale():$cultureCode;
    	$dateFormat = !empty($instanceData['date_format'])?$instanceData['date_format']:'m/d/Y';
    	
    	if (!$this->isClientRequest) {
    		
    		if (!empty($this->context->getToken()) && $this->context->isGranted('ROLE_ANONYMOUS') && $this->context->getToken()->getUser() != null) {
    			if ($this->context->getToken()->getUser()->getStatus() == 'active') {
    				$this->userId = $this->context->getToken()->getUser()->getId();
    				
    				$this->request->getSession()->set('userId', $this->userId); //$this->request->getSession()->get('userId', 1);
    			} else {
    				$this->context->setToken(null);
    				$this->request->getSession()->invalidate();
    			}
    			
    		} else {
    			$this->userId = 0;
    		}
    		$this->sessionManager = $this->request->getSession();
    	} else {
    		$this->request = $this->clientRequest ;
            if ($this->request->get('user_id')) {
                $this->userId = $this->request->get('user_id');
            } else {
                $this->userId = $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getFirstUserId($instanceId);
            }
    	}
    	
    	/*if ($this->userId > 0) {
    		$priceInDecimal = $priceInDecimal + 1;
    	}*/
    	
    	if (preg_match('/\/admin/',  $this->request->getRequestUri())) {
    		$instanceTheme = 'AdminTheme';
    	}
    	
    	$instaceThemePath = ($instanceTheme=='DefaultTheme' || $instanceTheme=='AdminTheme' || $instanceTheme=='DefaultCmsTheme' || $instanceTheme=='Ecommerce2Theme' || $instanceTheme=='DefaultEcommerceTheme' || $instanceTheme=='DefaultBlankTheme' || $instanceTheme=='DefaultBlankEcommerceTheme')?'OfficeBrainThemeBundle':'OfficeBrainCustomBundleThemeBundle';
    	$instanceFrontendThemePath = ($instanceTheme=='DefaultTheme' || $instanceTheme=='DefaultCmsTheme' || $instanceTheme=='Ecommerce2Theme' || $instanceTheme=='DefaultEcommerceTheme' || $instanceTheme=='DefaultBlankTheme' || $instanceTheme=='DefaultBlankEcommerceTheme')?'OfficeBrainThemeBundle':'OfficeBrainCustomBundleThemeBundle';

    	$rule_array1['project_setting'] = array(
    			'project_id' => $this->serviceContainer->getParameter('project_id'),
    			'instance_id' => $instanceId,
    			'instance_type' => $instanceType,
    			'instance_theme' => $instanceTheme,
    			'instance_frontend_theme' => $instanceFrontendTheme,
    			'instance_theme_path' => $instaceThemePath,
    			'instance_frontend_theme_path' => $instanceFrontendThemePath,
    			'locale_language' => $localLanguage,
    			'configuration_rule' => array(),
    			'culture_id' => $cultureId,
    			'culture_code' => $localLanguage,
    			'currency_code' => $currencyCode,
    			'currency_name' => $currencyName,
    			'price_in_decimal' => $priceInDecimal,
    			'base_url' => $this->request->getScheme().'://'.$this->host,
    			'instance_theme_mode' => 'publish',
    			'is_main_instance' => $isMainInstance,
    			'site_owner_id' => $siteOwnerId,
    			'allowed_culture' => $localLanguage,
    			'date_format' => $dateFormat
    	);
    	$this->request->attributes->add($rule_array1);
    	unset($rule_array1);
    	
    	
    }
    
    
    
    /**
     * @author Employee Id: 4273
     * Description : set instance Master Data
     *
     * */
    public function setInstanceMasterData()
    {
    	$instanceMaster = null;
    	$smode = '';
    	$stoken = trim($this->request->get('stoken'));
    	$referer = $this->request->headers->get('referer');
    	$allParameters = $this->request->attributes->all();
    	
    	if ($referer != '') {
    		$referer = parse_url($referer);
    		if (isset($referer['query'])) {
    			parse_str($referer['query'], $refererParameters);
    		}
    		if (isset($refererParameters['stoken'])) {
    			$stoken = $refererParameters['stoken'];
    		}

    		if (isset($refererParameters['smode'])) {
    			$smode = $refererParameters['smode'];
    		}

    		unset($referer);
    		unset($refererParameters);
    	}
    	
    	if ((!preg_match('{\/admin}',$this->request->getRequestUri())) && ($stoken != '') || (!$this->isClientRequest && !$this->event->isMasterRequest() && $this->sessionManager->has('stoken'))) {
    		if (!$this->isClientRequest && !$this->event->isMasterRequest() && $this->sessionManager->has('subsite_instance')) {
    			$instanceMaster = $this->sessionManager->get('subsite_instance');
    		} else {
    			$instanceMaster = $this->entityManager->getRepository('OfficeBrainAccessManagementBundle:InstanceMaster')->findBySubShopToken($stoken);
    			$this->sessionManager->set('subsite_instance', $instanceMaster);
    			$this->sessionManager->set('stoken', $stoken);
    		}
    	
    		$allParameters['project_setting']['instance_theme_mode']  = 'draft';
    	}

    	if ($smode != '') {
    		$allParameters['project_setting']['instance_theme_mode'] = $smode;
    		 
    		unset($smode);
    	}

    	if ($instanceMaster) {
    		$allParameters['project_setting']['instance_type']  = $instanceMaster->getInstanceType();
    		$allParameters['project_setting']['instance_id']    = $instanceMaster->getId();
    		$allParameters['project_setting']['instance_theme'] = $instanceMaster->getTheme()->getThemeName();
    		$allParameters['project_setting']['is_main_instance'] = $instanceMaster->getIsMain() == 1 ? true : false;
    		$instanceId = $allParameters['project_setting']['instance_id'];
    		$allParameters['project_setting']['instance_theme_path'] = ($allParameters['project_setting']['instance_theme']=='DefaultTheme' || $allParameters['project_setting']['instance_theme']=='AdminTheme' || $allParameters['project_setting']['instance_theme']=='DefaultCmsTheme' || $allParameters['project_setting']['instance_theme']=='Ecommerce2Theme' || $allParameters['project_setting']['instance_theme']=='DefaultEcommerceTheme' || $allParameters['project_setting']['instance_theme']=='DefaultBlankTheme' || $allParameters['project_setting']['instance_theme'] == 'DefaultBlankEcommerceTheme')?'OfficeBrainThemeBundle':'OfficeBrainCustomBundleThemeBundle';
    		$allParameters['project_setting']['instance_frontend_theme_path'] = ($allParameters['project_setting']['instance_theme']=='DefaultTheme' || $allParameters['project_setting']['instance_theme']=='AdminTheme' || $allParameters['project_setting']['instance_theme']=='DefaultCmsTheme' || $allParameters['project_setting']['instance_theme']=='Ecommerce2Theme' || $allParameters['project_setting']['instance_theme']=='DefaultEcommerceTheme' || $allParameters['project_setting']['instance_theme']=='DefaultBlankTheme' || $allParameters['project_setting']['instance_theme'] == 'DefaultBlankEcommerceTheme')?'OfficeBrainThemeBundle':'OfficeBrainCustomBundleThemeBundle';
    		$allParameters['project_setting']['site_owner_id']  = $instanceMaster->getOwnerId();
    	} elseif (!$this->isClientRequest && $this->sessionManager) {
    		if ($this->sessionManager->has('stoken')) {
    			$this->sessionManager->remove('stoken');
    		}
    	
    		if ($this->sessionManager->has('subsite_instance')) {
    			$this->sessionManager->remove('subsite_instance');
    		}
    	}
    	$this->request->attributes->add($allParameters);
    	unset($allParameters);
    	
    	
    }
    
    
    /**
     * @author Employee Id: 4273
     * Description : set Current User Data
     *
     * */
    public function setCurrentUserData()
    {
    	
      $this->statsh_cache_wrapper=RedisCacheService::create();
    	$serviceGroupId = null;
    	$allParameters = $this->request->attributes->all();
    	if (!$this->isClientRequest) {
    		if ($this->userId > 0) {
    			$userObj = $this->context->getToken()->getUser(); //$this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserById($this->userId, $instanceId);
    			if ($userObj->getServiceGroup()) {
    				$serviceGroupId = $userObj->getServiceGroup()->getId();
    			}
    		} else {
    			$userObj = null;
    			$serviceGroupId = null;
    		}
    	} else {
    		if ($this->userId > 0) {
    		  
    			$userObj = $this->entityManager->getRepository('OfficeBrainUserBundle:User')->getUserById($this->userId, $allParameters['project_setting']['instance_id']);
    			if ($userObj && $serviceGroupId = $userObj->getServiceGroup() != null) {
    				$serviceGroupId = $userObj->getServiceGroup()->getId();
    			}
    		} else {
    			$userObj = null;
    			$serviceGroupId = "";
    		}
    	}
    	
    	if ($serviceGroupId ==   null || $serviceGroupId == '') {
    		$country = $this->serviceContainer->getParameter('country');
    		$conid = explode('_', $allParameters['project_setting']['locale_language']);
    		$defaultGroup = null;
    		if (isset($conid[1])) {
    		    $cacheData=null;
            $this->moduleCachePrefix = '__UserManagement__';
            $cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('userServiceDefaultGroupData',$this->request->get('project_setting')['instance_id'], $this->request->get('project_setting')['instance_type']),$this->moduleCachePrefix);
            $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
            
            if($cacheData){
                $defaultGroup = $cacheData;
            }
            else {
                $defaultGroup = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceGroup')->getServiceDefaultGroupData($country[$conid[1]]['id'], $allParameters['project_setting']['instance_id'], $allParameters['project_setting']['instance_type']);
                RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$defaultGroup);
            }
    		}
    		if ($defaultGroup !=   null) {
    			$serviceGroupId = $defaultGroup->getId();
    		}
    	}

    	$allParameters['project_setting']['user_id'] = $this->userId;
    	$allParameters['project_setting']['service_group_id'] = $serviceGroupId;
    	$allParameters['project_setting']['admin_id'] = 1;
    	$allParameters['project_setting']['admin_email'] = $this->serviceContainer->getParameter('admin_email');
    	$allParameters['project_setting']['user_type'] = ($this->userId)?'registered':'guest';
    	$allParameters['project_setting']['menu_user_type'] = ($this->userId)? $userObj->getUserType() : 'public';
    	$allParameters['project_user_setting'] = array(
    			'user_data' => $userObj
    	);
    	$this->request->attributes->add($allParameters);
    	unset($allParameters);
    	//return $rule_array3;
    }
    
    
    /**
     * @author Employee Id: 4273
     * Description : set Access Rule Data
     *     
     * @param $instanceId
     * @param $userObj
     *
     * */
    public function setAccessRuleData()
    {
    	$allParameters = $this->request->attributes->all();
    	

    	$user_access_routes=array();
    	
    	$instance_access_routes=AccessManagementService::getInstanceAccessRoutes($this->entityManager, $this->request, $this->request->getSession(),$allParameters['project_setting']['instance_id']);
    	
    	$project_access_master=AccessManagementService::getProjectMasterAccessWiseUserAccess($this->entityManager, $this->request, $this->request->getSession(), $allParameters['project_user_setting']['user_data'], $allParameters['project_setting']['instance_id']);
    	
    	$allParameters['project_setting']['access_rule'] = $project_access_master;
    	$allParameters['project_setting']['user_access_routes'] = $user_access_routes;
    	$allParameters['project_setting']['instance_access_routes'] = $instance_access_routes;
    	$allParameters['project_setting']['instance_theme_meta'] = array();
    	
    	$this->request->attributes->add($allParameters);
    	unset($allParameters);
    	
    	
    }
    
    

    /**
     * @author Employee Id: 4273
     * Description : set Configuration Rule Data
     *
     *
     * */
    public function setConfigurationRuleData()
    {
        $this->statsh_cache_wrapper=RedisCacheService::create();
        $configuration_rule = array();
        $configuration_rule=AccessManagementService::getInstanceConfigurations($this->entityManager, $this->request, $this->request->getSession());
        $allParameters = $this->request->attributes->all();
        
        $allParameters['project_setting']['configuration_rule'] = $configuration_rule;
        // -----------------userApprovalConfiguration Start----------------------
        //$this->request->get('project_setting')['instance_id'], $this->request->get('project_setting')['instance_type']
        $cacheData=null;
        $this->moduleCachePrefix = '__UserManagement__';
        $cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('userApprovalConfiguration',$this->request->get('project_setting')['instance_id'],$this->request->get('project_setting')['instance_type']),$this->moduleCachePrefix);
        $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
        
        if($cacheData){
            $allParameters['project_setting']['configuration_rule']['user']['user_approval_configuration'] = $cacheData;
        }
        else {
            $userApprovalConfiguration=$this->entityManager->getRepository('OfficeBrainUserBundle:SignUpForm')->getUserApprovalConfiguration($this->request->get('project_setting')['instance_id'], $this->request->get('project_setting')['instance_type']);
            RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$userApprovalConfiguration);
            $allParameters['project_setting']['configuration_rule']['user']['user_approval_configuration'] = $userApprovalConfiguration;
        }
        // -----------------userApprovalConfiguration End----------------------
        $this->request->attributes->add($allParameters);
        unset($allParameters);
    }
    
    
    /**
     * @author Employee Id: 4273
     * Description : set Instance Theme Meta Data
     *
     * 
     * */
    public function setInstanceThemeMetaData()
    {   	
    	/* if some one enteres wrong culture for any subshop, redirect him to true culture */
    	if($this->isClientRequest != '1'  && isset($this->context) && is_object($this->context))
    	{
    		$token = $this->context->getToken();
    		
    		if (isset($token) && is_object($token)) {
    			$user = $token->getUser();
    			if(isset($user) && is_object($user))
    			{
    				$userType = ($user->getUserType());
    				if($userType=='end_user')
    				{
    					//echo "Redirect from ".$this->request->getLocale()." to ".$cultureCode.".";exit;
    					//print_r($this->request->getParam());die;
    					
    					$currentUrl = $this->request->getUri();
    					$adminSign = '/admin';

    					if(strstr($currentUrl,$adminSign))
    					{
    						$tempUrl = $this->router->generate('office_brain_userbundle_user_my_account_info');
    						$this->event->setResponse(new RedirectResponse(
    								$tempUrl
    								));
    					}
    				}
    			}
    		}
    		
    	}

    	$stoken = trim($this->request->get('stoken'));
    	
		$allParameters = $this->request->attributes->all();
		 
    	if ($allParameters['project_setting']['is_main_instance'] && $stoken != '') {
    		$allParameters['project_setting']['instance_theme_mode']  = $allParameters['project_setting']['user_id'] > 0 && count($allParameters['project_user_setting']['user_data']->getParent()) == 0 ? 'draft' : 'publish';
    	}
    	$customLabelStatus = 0;
    	if($allParameters['project_setting']['configuration_rule']['category']['status'] == 1 && $allParameters['project_setting']['configuration_rule']['category']['option']['custom_label'] == 1){
    		$customLabelStatus = 1;
    	}
    	
    	if (!$this->isClientRequest) {
      	  $this->moduleCachePrefix = '__InstanceThemeMetaData__';
      		$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('InstanceThemeMeta',$allParameters['project_setting']['instance_id'],$this->request->getLocale()),$this->moduleCachePrefix);
          $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
          if($cacheData) {
              $allParameters['project_setting']['instance_theme_meta']=$cacheData;
          }
          else {
              $allParameters['project_setting']['instance_theme_meta'] = $this->getSubShopThemeMeta($allParameters['project_setting']['instance_id'],$customLabelStatus);
              RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$allParameters['project_setting']['instance_theme_meta']);
          }
    	
          //=====================================================================
          $cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('ThemeLogo',$allParameters['project_setting']['instance_id'],$this->request->getLocale()),$this->moduleCachePrefix);
          $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
          if($cacheData) {
              $allParameters['project_setting']['theme_logo']=$cacheData;
          }
          else {
              $allParameters['project_setting']['theme_logo'] = $this->findLogo($allParameters['project_setting'], $this->serviceContainer->getParameter('country'), $this->serviceContainer->getParameter('language' ));
              RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$allParameters['project_setting']['theme_logo']);
          }
          //=====================================================================
        } else {
        	/* $this->moduleCachePrefix = '__InstanceThemeMetaData__';
        	$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('InstanceThemeMeta',$allParameters['project_setting']['instance_id'],$allParameters['project_setting']['locale_language']),$this->moduleCachePrefix);
        	$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
        	if($cacheData) {
        		$allParameters['project_setting']['instance_theme_meta']=$cacheData;
        	} */
        	$allParameters['project_setting']['instance_theme_meta'] = $this->getSubShopThemeMeta($allParameters['project_setting']['instance_id'],$customLabelStatus);
        }
        $this->request->attributes->replace($allParameters);

        unset($allParameters);

     }

      private function findInstance($event)
      {
          $this->statsh_cache_wrapper=RedisCacheService::create();
          $this->moduleCachePrefix = '__AccessManagement__';
          $accessMasterObj =  AccessManagementService::initFactory($this->entityManager, $this->request, $this->request->getSession());
          if (!empty($this->context->getToken()) && $this->context->isGranted('ROLE_API_ACCESS') ) {//For MobileApp : If current users uses API/has ROLE_API_ACCESS role then get instance_id and instance_type
              $instanceId = $this->request->get('instance_id',null);
              $instanceType = $this->request->get('instance_type',null);
              if( $instanceId != null && $instanceType != null ){
                  
                  $cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('findInstance',$instanceId,$instanceType),$this->moduleCachePrefix);
                  $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
                  if($cacheData) {
                      return $cacheData;
                  }
                  
                  $instanceData = $accessMasterObj->getInstanceMasterRepo()->findByInstanceIdType($instanceId, $instanceType);
                  if(!$instanceData){
                      throw new AccessDeniedException( "incorrect value of instance_id and instance_type.");
                  }
              }
              else{
                    throw new AccessDeniedException( "provide value for instance_id and instance_type.");
                }
          }
          else
          {//For website
                $hostName = $this->host;
                $subDomain = null;
                preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $hostName, $subDomain);
                if(!empty($hostName) && $hostName!='localhost' && empty($subDomain)){
                    $hostName = "www.".$hostName;
                }
                
                $cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('findInstance',$hostName),$this->moduleCachePrefix);
                $cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
                if($cacheData) {
                    return $cacheData;
                }
                
                if($event){
                    $instanceData = $accessMasterObj->getInstanceMasterRepo()->findByDomain($hostName);
                }
                else {
                    $instanceData = $accessMasterObj->getInstanceMasterRepo()->getMainInstanceMasterObject()[0];
                }
                
                if(!empty($event) && empty($instanceData) && isset($GLOBALS['instanceId']) && !empty($GLOBALS['instanceId'])){
                    $instanceData = $accessMasterObj->getInstanceMasterRepo()->find($GLOBALS['instanceId']);
                }
          }
          
          $arrInstanceData=array();
          if (!empty($instanceData)) {
              $arrInstanceData['instance_type']  = $instanceData->getInstanceType();
              $arrInstanceData['instance_id']    = $instanceData->getId();
              $arrInstanceData['instance_theme'] = $instanceData->getTheme()->getThemeName();
              $arrInstanceData['site_owner_id'] = $instanceData->getOwnerId();
              $arrInstanceData['is_main_instance'] = $instanceData->getIsMain() == 1 ? true : false;
              $arrInstanceData['culture_id'] = $instanceData->getCultureId();
              $arrInstanceData['culture_code'] = $instanceData->getCultureCode();
              $arrInstanceData['currency_code'] = $instanceData->getCurrencyCode();
              $arrInstanceData['currency_name'] = $instanceData->getCurrencyName();
              $arrInstanceData['price_in_decimal'] = $instanceData->getPriceInDecimal();
              $arrInstanceData['alias_domain'] = $instanceData->getAliasDomain();
              $arrInstanceData['date_format'] = $instanceData->getDateFormat();
              if (!empty($instanceData->getAllowedCulture())) {
                  $arrInstanceData['allowed_culture'] = explode(',', $instanceData->getAllowedCulture());
              }
          }
          
          RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$arrInstanceData);
          
          return $arrInstanceData;
      }

    private function findLogo($projectSetting, $country, $language)
    {
        $countryId = $languageId = 0;
        $countryCode = $languageCode = '';

        $return = array('title' => '', 'link' => '','image' => '');

        if (isset($projectSetting['instance_theme_meta']['theme_data']['header_logo_area'])) {
            $logoDetail = $projectSetting['instance_theme_meta']['theme_data']['header_logo_area'];

            $return['title'] = $logoDetail['title'];
            $return['link'] = $logoDetail['link'];
            $return['image'] = $logoDetail['image'];

            $localeLanguage = explode('_', $projectSetting['locale_language']);
            if (count($localeLanguage) > 1) {
                list($languageCode, $countryCode) = $localeLanguage;
            }

            if (isset($country[$countryCode])) {
                $countryId = $country[$countryCode]['id'];
            }

            if (isset($language[$languageCode])) {
                $languageId = $language[$languageCode]['id'];
            }

            if (isset($logoDetail[$countryId][$languageId])) {
                if ($logoDetail[$countryId][$languageId]['image'] != '') {
                    $return = $logoDetail[$countryId][$languageId];
                }
            }
        }

        return $return;
    }
    
    public function getSubShopThemeMeta($instanceId,$customLabelStatus)
    {
    	$data = array('theme_area' => array(), 'theme_data' => array(), 'token' => $this->request->get('stoken'),'product_category' => array());
    
    	$subShopInstanceMeta = $this->entityManager->getRepository('OfficeBrainSubShopBundle:SubshopInstanceMeta')->findByMetaKey('theme_area', $instanceId);
    
    	if ($subShopInstanceMeta) {
    		$data['theme_area'] = json_decode($subShopInstanceMeta->getMetaValue(), 'array');
    	}
    
    	$subShopInstanceMeta = $this->entityManager->getRepository('OfficeBrainSubShopBundle:SubshopInstanceMeta')->findByMetaKey('theme_data', $instanceId);
    
    	if ($subShopInstanceMeta) {
    		$data['theme_data'] = json_decode($subShopInstanceMeta->getMetaValue(), 'array');
    	}
    	
    	if($customLabelStatus == 1){
	    	$subShopInstanceMeta = $this->entityManager->getRepository('OfficeBrainSubShopBundle:SubshopInstanceMeta')->findByMetaKey('product_category', $instanceId);
	    	if($subShopInstanceMeta){
	    		$data['product_category'] = json_decode($subShopInstanceMeta->getMetaValue(), 'array');
	    	}
    	}
    	unset($subShopInstanceMeta);
    	return $data;
    }
}