<?php

namespace OfficeBrain\Bundle\CoreBundle\TwigExtension;

use OfficeBrain\Bundle\CoreBundle\Helper\Processor;

class Extension extends \Twig_Extension
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    protected $coreLibraryManager;

    protected $subShopManager;

    protected $container;

    public function __construct(Processor $processor, $container, $coreLibraryManager)
    {
        $this->processor = $processor;
        $this->coreLibraryManager = $coreLibraryManager;
        $this->container = $container;
    }

    public function initRuntime(\Twig_Environment $environment)
    {
        $this->environment = $environment;
    }

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('to_array', array($this, 'to_array')),
            new \Twig_SimpleFilter('to_object', array($this, 'to_object')),
            new \Twig_SimpleFilter('rating', array($this, 'ratingFilter')),
            new \Twig_SimpleFilter('unset', array($this, 'unsetFilter')),
            new \Twig_SimpleFilter('country', array($this, 'getCountryName')),
        	new \Twig_SimpleFilter('countryCode', array($this, 'getCountryCode')),
            new \Twig_SimpleFilter('state', array($this, 'getStateName')),
            new \Twig_SimpleFilter('city', array($this, 'getCityName')),
            new \Twig_SimpleFilter('address_type', array($this, 'getAddressType')),
        	new \Twig_SimpleFilter('service_group', array($this, 'getServiceGroupName')),
            new \Twig_SimpleFilter('dateFormat', array($this, 'dateFormatFilter')),
        	new \Twig_SimpleFilter('dateTimeFormat', array($this, 'dateTimeFormatFilter')),
        	new \Twig_SimpleFilter('dateFormatQuote', array($this, 'dateFormatQuoteFilter')),
            new \Twig_SimpleFilter('dateCreate', array($this, 'dateCreateFilter')),
        	new \Twig_SimpleFilter('getClassName', array($this, 'getClassNameFilter')),
        	new \Twig_SimpleFilter('printr', array($this, 'getPrintFilter')),
        	new \Twig_SimpleFilter('logo', array($this, 'logo')),
        	new \Twig_SimpleFilter('currency', array($this, 'currencyFilter')),
        	new \Twig_SimpleFilter('tag', array($this, 'tagFilter')),
        	new \Twig_SimpleFilter('json_decode', array($this, 'json_decode')),
        	new \Twig_SimpleFilter('product_image_url', array($this, 'productImageUrl')),
        	new \Twig_SimpleFilter('product_thumb_image_url', array($this, 'productThumbImageUrl')),
        	new \Twig_SimpleFilter('splitCulture', array($this, 'splitCultureFilter')),
        	new \Twig_SimpleFilter('youtubeUrl', array($this, 'youtubeUrlFilter')),
        	new \Twig_SimpleFilter('ksort', array($this, 'ksortFilter')),
        	new \Twig_SimpleFilter('krsort', array($this, 'krsortFilter')),
        	new \Twig_SimpleFilter('replaceUnderScore', array($this, 'replaceUnderScoreFilter')),
        	new \Twig_SimpleFilter('getYear', array($this, 'getYearFilter')),
        	new \Twig_SimpleFilter('getMonth', array($this, 'getMonthFilter')),
        	new \Twig_SimpleFilter('userPhotoById', array($this, 'getUserPhoto')),
            new \Twig_SimpleFilter('slice_array', array($this, 'sliceArray')),
        	new \Twig_SimpleFilter('feedBack', array($this, 'feedBackFilter')),
        	new \Twig_SimpleFilter ( 'calculateTax', array ($this,'calculateTaxFilter') ),
        	new \Twig_SimpleFilter ( 'price', array ($this,'priceFilter') ),
        	new \Twig_SimpleFilter ( 'getDistributorForHide', array ($this,'getDistributorForHideFilter') ),
            new \Twig_SimpleFilter ( 'html_entities', array ($this,'htmlEntities') ),
        	new \Twig_SimpleFilter('removeThumb', array($this, 'removeThumbFilter')),
        	new \Twig_SimpleFilter('removeCulture', array($this, 'removeCultureFilter')),
        	new \Twig_SimpleFilter ( 'getDistributorCompanyName', array ($this,'getDistributorCompanyNameFilter') ),
        	new \Twig_SimpleFilter ( 'calculateTaxShippingWise', array ($this,'calculateTaxShippingWiseFilter') ), // This is for TPW
        	new \Twig_SimpleFilter ( 'dateJsFormat', array ($this,'dateJsFormatFilter') ),
        	new \Twig_SimpleFilter ( 'arrayCountLength', array ($this,'innerArrayCountLength') ),
        	new \Twig_SimpleFilter ( 'displayCurrencySymbol', array ($this,'removeCurrencyNameFilter') ),
        	new \Twig_SimpleFilter ( 'sortByKey', array ($this,'sortByKeyFilter') ),
        	new \Twig_SimpleFilter ( 'sortByField', array ($this,'sortByFieldFilter') ),
            new \Twig_SimpleFilter('base64_decode', array($this, 'base64_decodeFilter')),
            new \Twig_SimpleFilter('deserialize', array($this, 'deserializeFilter')),
        	new \Twig_SimpleFilter('characterCount', array($this, 'characterCountFilter')),
        	new \Twig_SimpleFilter('displayOtherColor', array($this, 'displayOtherColorFilter')),     
			new \Twig_SimpleFilter('currentCounty', array($this, 'currentCounty')), 
            new \Twig_SimpleFilter('shortcode',array($this, 'shortcodeFilter')),    
        );
    }

    /**
     * Custom logic for the raw filter
     */
    public function shortcodeFilter($html)
    {
        $pattern = '/\["source=FlipBook","id=(\d+)"\]/';
        //$pattern = '/\["source=FlipBook","id=(\d+)","rows=(\d+)"\]/';

        preg_match_all($pattern, $html, $matches);
        $shortCode = NULL;
        
        if(count($matches)>0){

            if(isset($matches[0][0])){
                $string = trim($matches[0][0], '[]');
                $string = trim($string, '"');
                $items = explode('","', $string);
                foreach ($items as $item) {
                    list($key, $value) = explode('=', $item);
                    $shortCode[$key] = $value;
                }
            }
           
            if(isset($shortCode['source']) && isset($shortCode['id'])){
               $iframe ="";
               $flipBookManager = $this->container->get('office_brain_flip_book_manager');
               $entity = $flipBookManager->getById($shortCode['id'],'Active');
               if($entity!=NULL){
                    $rows = ($entity->getNoOfRows()==0) ? '1' :  $entity->getNoOfRows();
                    $height = $rows*480; //die;
                    $iframe = '<iframe src="'.$entity->getEmbedLink().'" width="100%" height="'.$height.'" seamless="seamless" scrolling="no" frameBorder="0" allowFullScreen allow="autoplay; clipboard-read; clipboard-write"></iframe>';

                    $html = preg_replace($pattern, $iframe, $html);
                }else{
                    $html = preg_replace($pattern, $iframe, $html);
                }
            }
        }
        echo $html;
    }

    /**
     * @author Employee Id: 4846
     * OB eCommerce Product - Twig Extension
     * Filter created to calculate tax shipping wise
     */
    public function calculateTaxShippingWiseFilter($taxinfo){
    	$allowedStates=array("NY");
    	$allowedCategories=array("492");
    	
    	$stateCode=$taxinfo['stateCode'];
    	$tax=0;
    	if(is_array($taxinfo['productCategory']) && count($taxinfo['productCategory'])>0 && !empty($stateCode)) {
    		$productCategory=array_keys($taxinfo['productCategory']);
    		if(in_array($stateCode,$allowedStates)){
    			if(count(array_intersect($allowedCategories, $productCategory))>0) {
    				$tax='4.75';
    			} else {
    				$tax='8.75';
    			}
    		}
    	}
    	return $tax;
    }
    public function removeCultureFilter($str){
    	$part= explode('-1',$str);
    	return $slug = $part[0];
    }
    
    public function removeCurrencyNameFilter($str){
    	$part= str_replace("CAD ($)","$",str_replace("USD ($)","$",str_replace("NOK (kr)","kr",$str)));
    	return $part;
    }
    
    public function removeThumbFilter($str){
    	$part= explode('thumb/',$str); 
    	return $image = $part[0].$part[1];
    }
    public function priceFilter($price)
    {
    	$decimal = $this->coreLibraryManager->getDecimalPointForPrice();
    	if(is_numeric($price)) {
    		$formatter = $this->coreLibraryManager->getPriceFormater();
    		$curr = $formatter['price_currency'];
    		
    			return number_format($price, $decimal, '.', '');
    	}
    	
    }
    
    /* public function getDistributorForHideFilter($value) {
    	return '89';
    } */
    
 	public function getDistributorForHideFilter($value){
    	$siteOwnerId= $this->coreLibraryManager->getSiteOwnerId();
    	$this->coreLibraryManager->updateLocatedDistId($siteOwnerId);
    	return $siteOwnerId;
    }

    public function calculateTaxFilter($array) {
    	if($array['vat_unit']=="percentage"){
    		return (float) $array['vat']/100;
    	}else{
    		return $array['vat'];
    	}
    }

    public function feedBackFilter($array)
    {
    	return base64_encode(json_encode($array));
    }
    public function getYearFilter($array)
    {
    	return date('Y');
    }
    public function getMonthFilter($array)
    {
    	return date('M');
    }
    public function replaceUnderScoreFilter($str)
    {
    	$data=explode('_',$str);
    	$string='';
    	foreach($data as $value){
    		if($string!=''){
    			$string.=ucfirst($value);
    		}else{
    			$string=$value;
    		}
    	}
    	echo $string;
    }
    public function getPrintFilter($array)
    {
    	echo "<pre>";
    	print_r($array); die;
    }

    public function splitCultureFilter($locale)
    {
		$arrLocale = array('culture' => '','countryCode' => '');
      	$tmpLocale = explode("_", $locale);
      	if(!empty($arrLocale)) {
			$arrLocale['culture'] = $tmpLocale[0];
          	$arrLocale['countryCode'] = $tmpLocale[1];
      	}
      	unset($tmpLocale);

      	return $arrLocale;
    }

    public function getClassNameFilter($data){
    	return get_class($data);
    }

    public function ksortFilter($array)
    {
    	ksort($array);
    	return $array;
    }

    public function krsortFilter($array)
    {
    	krsort($array);
    	return $array;
    	    }
    public function dateJsFormatFilter($data){
    	return $this->coreLibraryManager->getDateJsFormat($data);
    }

    public function dateFormatQuoteFilter($date, $format=null)
    {
    	if ($format) {
    		return $date->format($format);
    	}
    	else {
        	return $date->format('m/d/Y');
    	}
    }

	public function dateFormatFilter($date, $format=null)
    {
    	if (gettype($date)=='string') {
    		return date($format, strtotime($date));
    	}
    	else {
	    	if ($format) {
	    		return $date->format($format);
	    	}
	    	else {
	        	return $date->format('m/d/Y');
	    	}
    	}
    }
    
    public function dateTimeFormatFilter($date, $format=null)
    {
    	if (gettype($date)=='string') {
    		return date($format, strtotime($date));
    	}
    	else {
    		return $date->format('m/d/Y h:i:s');
    	}
    }
    
    public function dateCreateFilter($date)
    {
    	$getDate = date_create($date);
        return $getDate->format('m/d/Y');
    }

	public function json_decode($data)
    {
        return json_decode($data,true);
    }
    public function getFunctions()
    {
        return array(
                'office_brain_pagination_render' => new \Twig_Function_Method($this, 'numberPaginatorRender', array('is_safe' => array('html'))),
                //'knp_pagination_sortable' => new \Twig_Function_Method($this, 'sortable', array('is_safe' => array('html'))),
                //'knp_pagination_filter' => new \Twig_Function_Method($this, 'filter', array('is_safe' => array('html'))),
        );
    }

    public function numberPaginatorRender($paginationType, $formId, $pagination, $template = null, array $queryParams = array(), array $viewParams = array())
    {
        return $this->environment->render(
                $template ?: $pagination->getTemplate(),
                $this->processor->render($paginationType, $formId, $pagination, $queryParams, $viewParams)
        );
    }

    public function to_array($object)
    {
        return get_object_vars($object);
    }

    public function to_object($object)
    {
        return (object) $object;
    }

    public function getName()
    {
        return 'web_extension';
    }

    public function ratingFilter($numberOfRating)
    {
        $maxStar = 5;
        $ratingHtml = array();
        $showHalfStart = false;

        if ($numberOfRating>$maxStar) {
            $numberOfRating = $maxStar;
        }

        if (strpos($numberOfRating, ".") == true) {
            $temp = floor($numberOfRating);
            $fraction = $numberOfRating - $temp;
            $fullStart = $temp;
            $showHalfStart = true;
        } else {
            $fullStart = $numberOfRating;
        }
        $emptyStart = $maxStar-$numberOfRating;

        for ($index=1; $index<=$fullStart; $index++) {
            $ratingHtml[] = '<i class="fa fa-star"></i>';
        }
        if ($showHalfStart) {
            $ratingHtml[] = '<i class="fa fa-star-half-o"></i>';
        }
        for ($index=1 ;$index<=$emptyStart; $index++) {
            $ratingHtml[] = '<i class="fa fa-star-o"></i>';
        }
        unset($maxStar);
        unset($fullStart);
        unset($emptyStart);
        unset($numberOfRating);

        return implode('', $ratingHtml);
    }

    public function sliceArray($array,$noOfSlices = 2)
    {
        $newArray = array_chunk($array, ceil(count($array) / $noOfSlices), true);
        return $newArray;
    }

    /**************************Tag Html filter*****************************/

    public function tagFilter($tag)
    {
    	$tagExplodeByPipe = explode(" | ",$tag);
    	return '<div><div class="product-label '.$tagExplodeByPipe[3].'"><h2 class="logo"><i class="fa '.$tagExplodeByPipe[2].'"></i>'.$tagExplodeByPipe[1].'</h2></div></div>';
    }

    public function unsetFilter($array, $key)
    {
        unset($array[$key]);
        return $array;
    }

    public function getCountryName($countryId)
    {
        return $this->coreLibraryManager->getCountryName($countryId);
    }

    public function getCountryCode($countryId) {
    	return $this->coreLibraryManager->getCountryCode ( $countryId );
    }

    public function getStateName($stateId)
    {
        return $this->coreLibraryManager->getStateName($stateId);
    }

    public function getCityName($cityId)
    {
        return $this->coreLibraryManager->getCityName($cityId);
    }

    public function getAddressType($addressTypeId)
    {
        return $this->coreLibraryManager->getAddressType($addressTypeId);
    }

    public function getServiceGroupName($serviceGroupId)
    {
    	return $this->coreLibraryManager->getServiceGroupName($serviceGroupId);
    }

    public function logo($image)
    {
    	$logo = $this->coreLibraryManager->getLogo();

    	if ($logo != '') {
    		$image = $logo;
    	}
    	return $image;
    }

    public function currencyFilter($number)
    {
    	if($number == 'N/A')
    	{
    		return $number;
    	}
    	if(is_numeric($number)) {
    		$number = number_format($number, $decimal = $this->coreLibraryManager->getDecimalPointForPrice(), '.', '');
    		$formatter = $this->coreLibraryManager->getPriceFormater();
    		if($formatter['user_id']>0) {
    			$priceDec = $formatter['price_decimal_place'];
    		}
    		else {
    			$priceDec = $formatter['price_decimal_place'];
    		}
    		$curr = $formatter['price_currency'];
    		if ($curr == "INR"){
    			return $this->coreLibraryManager->formatinr($number);
    		} else {
    			if($number == 0 || $number == '0.00') {
    				if($formatter['user_id']>0) {
    					return '0.00';
    				}
    				else {
    					return '0.00';
    				}
    			}
    			else {
    				return number_format($number, $priceDec, $formatter['price_decimal_separate'], $formatter['price_in_decimal_separate']);
    			}
    		}
    	}
    	return null;
    }

    public function productImageUrl($colorId, $imageUrl, $imageId){
    	$productImageUrl = '';
    	$continue = 0;
    	foreach($imageId as $key => $value){
    		if($colorId == $value && $continue == 0){
    			$productImageUrl = $imageUrl[$key];
    			$continue = 1;
    		}
    	}
    	return $productImageUrl;
    }

    public function productThumbImageUrl($colorId, $imageUrl, $imageId){
    	$productThumbImageUrl = '';
    	$continue = 0;
    	foreach($imageId as $key => $value){
    		if($colorId == $value && $continue == 0 && !empty($imageUrl[$key])){
    			$tempImgUrl = $imageUrl[$key];
    			$tempImgUrl = explode('/',$tempImgUrl);
    			$tempImgUrl[count($tempImgUrl)] = $tempImgUrl[count($tempImgUrl)-1];
    			$tempImgUrl[count($tempImgUrl)-2] = 'thumb';
    			$tempImgUrl = implode('/',$tempImgUrl);
    			$productThumbImageUrl = $tempImgUrl;
    			$continue = 1;
    		}
    	}
    	return $productThumbImageUrl;
    }
    
    public function youtubeUrlFilter($url)
    {
    	return 'https://www.youtube.com/embed/'.preg_replace("/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", "$2", $url);
    }

    public function getUserPhoto($userId)
    {
    	return $this->coreLibraryManager->getUserPhoto($userId);
    }
    
    public function htmlEntities($string) {
        //return htmlentities($string, ENT_IGNORE, "UTF-8");
        return html_entity_decode($string);
    }
    public function getDistributorCompanyNameFilter($userId){
    	return $this->coreLibraryManager->getDistributorCompanyName($userId);
    }
    /**
     * @author Employee Id: 4014
     * OB eCommerce Product - Twig Extension
     * Filter created to count length of inner arrays
     */
    public function innerArrayCountLength($mainArray){
    	$count=0;
    	foreach($mainArray as $innerArray)
    	{
    		if($innerArray['count']>0)
    		{
    			$count++;
    		}
    
    	}
    	return $count;
    }
    
    /**
     * Filter to sort array by key
     * @author : 5540
     * @param unknown $array
     */
    public function sortByKeyFilter($array)
    {
    	ksort($array);
    	
    	return $array;
    }
    
	/**
     * Filter to sort array by field
     * @author : 5497
     * @param unknown $array
     */
    public function sortByFieldFilter($array)
    {
    	$catList = array();
		foreach ($array as $id=>$val) {
			$catList[$val['slug']] = $val['cat_name'];
		}
		ksort($catList);
		
    	return $catList;
    }

    /**
     * Filter to base64_decode string
     * @author : 5265
     * @param unknown $array
     */
    public function base64_decodeFilter($str){
        return base64_decode($str);
    }

    /**
     * Filter to deserialize string
     * @author : 5265
     * @param unknown $array
     */
    public function deserializeFilter($serializeStr){
        return unserialize($serializeStr);
    }
    
    public function characterCountFilter($arrayData){
		$str = "";
		$temp = array();
		$arrayData = array_map('strtolower', $arrayData);
		for($i=0;$i<count($arrayData);$i++)
		{
			if($arrayData[$i] == $arrayData[$i+1]){
				$temp[] = $arrayData[$i]; 
			}			
			elseif ($arrayData[$i] != $arrayData[$i+1]){
				if(count($temp) >0 ){
					$k = count($temp)+1;
					$str = $str.$k."".$arrayData[$i];
					$temp =array();
				}else{
					$str .= $arrayData[$i];
				}
			}
		}
		$str = strtoupper($str);
		return $str;
    }
    
    public function displayOtherColorFilter($extraColor, $productAttr){

    	$extraColorRes = unserialize($extraColor);
    	$result = array();
    	$i = 0;
    	foreach($extraColorRes as $ext_colo_key=>$ext_colo_val){
    		$str_color = '';
    		foreach($productAttr as $attr_key=>$attr_val){
    			if($attr_val['id'] == $ext_colo_key){
    				$lable = str_replace('Colors','',$attr_val['label']);
    				$str_color = $lable.' : ';
    			}
    		}
    		foreach($productAttr as $attr_key=>$attr_val){
    			if($attr_val['id'] == '10'){
    				$str_color = $str_color . $attr_val['values'][$ext_colo_val];
    				$result[$i] = $str_color;
    				$i++;
    			}
    		}
    	}
    	return $result;
    }
    
    public function currentCounty($oldLocale)
    {
    	$newLocale= isset($_COOKIE["CUSTOM_SITE_CULTURE"])?$_COOKIE["CUSTOM_SITE_CULTURE"]:'en_us';
    	$country = (isset($newLocale) && $newLocale!=null)?$newLocale:$oldLocale;
    	
//     	if((!isset($caMinPrice) || $caMinPrice== null) && $newLocale == 'en_ca')
//     	{
//     		$country = 'en_us';
//     	}
    	
    	$newCountry =explode("_",$country);
    	
    	if(isset($newCountry[1]))    
    		return $newCountry[1];
    	else 
    		return 'us';
    }
}
