<?php
 
namespace OfficeBrain\Bundle\CoreBundle\Library;

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\DependencyInjection\ContainerInterface;

class OBCommon
{
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
        
    public function __destruct()
    {
        unset($this->container);
    }
	
    public function getRouteNameFromUrl($url) {
		if ($url==null) {
    			return null;
    	}
    	$baseUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
    	$baseUrl = str_replace(array('/app.php', '/app_dev.php', '/app_qa.php'), '', $baseUrl); 
    	$url = str_replace(array('/app.php', '/app_dev.php', '/app_qa.php'), '', $url);
    	$url = str_replace($baseUrl, '', $url);
    	if (!$url) {
			$url = '/';
		}
		unset ( $baseUrl );
		try {
			try {
				$routeInformation = $this->router->getMatcher ()->match ( $url );
				return $routeInformation ['_route'];
			} catch ( MethodNotAllowedException $e ) {
				return null; 
			} 
		}
		catch (ResourceNotFoundException $e) {
		 	return null; 
		} 
    }
    /* public static function getRouteNameFromUrl($url, $SfRequest, $SfRouter)
    {
        if ($url==null) {
            return null;
        }

        $routeInformation = null;
                
        $urlPara = parse_url($url);

        $url = $urlPara['path'];
        $url = $urlPara['scheme'].'://'.$urlPara['host'].$urlPara['path'];
        $base_url = $urlPara['scheme'].'://'.$urlPara['host'];
        //$url = substr($url, strpos($url, $SfRequest->getBaseUrl()));
        $url = substr($url, strpos($url, $base_url));
        $url = str_replace($base_url, '', $url);
        if (!$url) {
            $url = '/';
        }
        
        try {
            $routeInformation = $SfRouter->getMatcher()->match($url);
            //echo $routeInformation; die;
            $routeInformation = $routeInformation['_route'];
             
            unset($url);
            unset($urlPara);
            unset($SfRequest);
            unset($SfRouter);
            return $routeInformation;
        } catch (MethodNotAllowedException $e) {
            return null;
        }
    } */
    
    public static function getTrimValue($string)
    {
        return trim($string);
    }


    /**
     *  @author 4072
     *   to upload user logo image
     *
     *  @return string : name of uploaded user logo image
     */
    public function uploadUserImage($user, $formData)
    {
        $image = $formData->get('image')->getData();
        if (null === $image) {
            return;
        }
    
        $imagename = $image->getClientOriginalName();
        $imagename = $this->resetImageName($imagename);
        $uploadDir = $this->getUserImageUplodFullPath($user);
    
        $user->getImage()->move(
                $uploadDir,
                $imagename
        );
        return $imagename;
    }
    
    /**
     *  @author 4072
     *   to get new image name of uploaded user logo
     *
     *  @param string initialVal: to fetch data by this value
     *
     *  @return string : new image name of uploaded user logo
     */
    public function resetImageName($imagename)
    {
        $imgPathAry = pathinfo($imagename);
        $imgPathAry['filename'] = preg_replace('/[^a-z0-9]+/i', '_', $imgPathAry['filename']);
        $imagename = $imgPathAry['filename'].'-'.time().'.'.$imgPathAry['extension'];
        return $imagename;
    }
    
    /**
     *  @author 4072
     *   to get Full Path of user logo image
     *
     *  @return string : get Full Path of user logo image
     */
    public function getUserImageUplodFullPath($user)
    {
        return $this->getImageUploadRootDir($this).$this->getUserLogoUploadPath();
    }
    
    /**
     *  @author 4072
     *   to get Full URL of user logo image
     *
     *  @return string : get Full URL of user logo image
     */
    public function getUserImageUplodFullURL()
    {
        return ($this->container->get('router')->getContext()->getBaseUrl().$this->getUserLogoUploadPath());
    }
    
    /**
     *  @author 4072
     *   to get User logo path folder
     *
     *  @return string:logo path folder
     */
    public function getUserLogoUploadPath()
    {
        return $this->container->getParameter('user_logo_path');
    }
    
    /**
     *  @author 4072
     *   to remove/delete image from server
     *
     *  @param string imageName: name of user logo image
     */
    public function unsetUserImage($imageName, $user)
    {
        unlink($this->getUserImageUplodFullPath($user).$imageName);
        //remove Thumb image
        unlink($this->getUserImageUplodFullPath($user).'thumb_image_100x100'.$this->getUserLogoUploadPath().$imageName);
    }
    /**
     * Get Upload Dir Path
     *
     * @return string
     */
    public function getImageUploadRootDir()
    {
        return $this->container->get('kernel')->getRootDir().'/../web' ;
    }
    
    /**
     * Convert under_score type array's keys to camelCase type array's keys
     * @param array $array array to convert
     * @param array $arrayHolder parent array holder for recursive array
     * @return array camelCase array
     */
    public function camelCaseKeys($array, $arrayHolder = array())
    {
        $camelCaseArray = !empty($arrayHolder) ? $arrayHolder : array();
        //print_r($array);
        foreach ($array as $key => $val) {
            $newKey = @explode('_', $key);
            array_walk($newKey, create_function('&$v', '$v = ucwords($v);'));
            $newKey = @implode('', $newKey);
            $newKey{0}
            = strtolower($newKey{0});
            //if (!is_array($val)) {
                $camelCaseArray[$newKey] = $val;
            //} else {
            //	$camelCaseArray[$newKey] = $this->camelCaseKeys($val, $camelCaseArray[$newKey]);
            //}
        }
        
        return $camelCaseArray;
    }

    /**
     * Convert camelCase type array's keys to under_score+lowercase type array's keys
     * @param array $array array to convert
     * @param array $arrayHolder parent array holder for recursive array
     * @return array under_score array
     */
    public function underscoreKeys($array, $arrayHolder = array())
    {
        $underscoreArray = !empty($arrayHolder) ? $arrayHolder : array();
        foreach ($array as $key => $val) {
            $newKey = preg_replace('/[A-Z]/', '_$0', $key);
            $newKey = strtolower($newKey);
            $newKey = ltrim($newKey, '_');
            if (!is_array($val)) {
                $underscoreArray[$newKey] = $val;
            } else {
                $underscoreArray[$newKey] = $this->underscoreKeys($val, $underscoreArray[$newKey]);
            }
        }
        return $underscoreArray;
    }
    
    /**
     * Convert camelCase type array's values to under_score+lowercase type array's values
     * @param mixed $mixed array|string to convert
     * @param array $arrayHolder parent array holder for recursive array
     * @return mixed under_score array|string
     */
    public function underscoreValues($mixed, $arrayHolder = array())
    {
        $underscoreArray = !empty($arrayHolder) ? $arrayHolder : array();
        if (!is_array($mixed)) {
            $newVal = preg_replace('/[A-Z]/', '_$0', $mixed);
            $newVal = strtolower($newVal);
            $newVal = ltrim($newVal, '_');
            return $newVal;
        } else {
            foreach ($mixed as $key => $val) {
                $underscoreArray[$key] = $this->underscoreValues($val, $underscoreArray[$key]);
            }
            return $underscoreArray;
        }
    }
    public function formRequestFormCheck($data, $form)
    {
        print("REQUEST DATA<br/>");
        foreach ($data as $k => $d) {
            print("$k: <pre>");
            print_r($d);
            print("</pre>");
        }
            
        $children = $form->all();
            
        print("<br/>FORM CHILDREN<br/>");
        foreach ($children as $ch) {
            print($ch->getName() . "<br/>");
        }
            
        $data = array_diff_key($data, $children);
        //$data contains now extra fields
            
        print("<br/>DIFF DATA<br/>");
        foreach ($data as $k => $d) {
            print("$k: <pre>");
            print_r($d);
            print("</pre>");
        }
    }
    
    public function get_array_column($array, $columnKey, $indexKey='')
    {
        $newAry = array();
        if ($indexKey=='key') {
            foreach ($array as $k=>$a) {
                $newAry[$k] = $a[$columnKey];
            }
        } else {
            foreach ($array as $a) {
                if (isset($a[$indexKey])) {
                    $newAry[$a[$indexKey]] = $a[$columnKey];
                } else {
                    $newAry[] = $a[$columnKey];
                }
            }
        }
        return $newAry;
    }
        
        /**
        * @author Employee Id: 4589
        * Description : seprate culture with language and country.
        *
        * @param string $culture
        *
        * @return array
        */
        public function getCultureValue($culture)
        {
            $cultures = explode("_", $culture);
            return $cultures;
        }
}
