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

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;

class OBCommon
{
    public function __construct($request, $router, $validator)
    {
        $this->request = $request;
        $this->router = $router;
        $this->validator = $validator;
        $this->formErrorManager = new FormErrorManager\JsonError();
    }
        
    public function __destruct()
    {
        unset($this->request);
        unset($this->router);
        unset($this->validator);
    }

    public function getRefererUrl()
    {
    	if (!array_key_exists('HTTP_REFERER', $_SERVER)) {
    		return null;
    	}
    	$refererUrl = $_SERVER["HTTP_REFERER"];
        $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'), '', $refererUrl);
        
        $refererUrl = str_replace($baseUrl, '', $url);
        if (!$refererUrl) { 
        	$refererUrl = '/';
       	}
        unset($baseUrl);

		return $refererUrl;
    }

    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 function getRefererRouteName()
    {
        return $this->getRouteNameFromUrl($this->request->headers->get('referer'));
    }
    
    public function getProductPriceByQty($columnPriceArray, $qty)
    {
    	//if($productDetailArray['data'][$productId]['price_type'] == "regular" ){
    		if((array_key_exists("decorative",$columnPriceArray))){
    			$priceRange = $columnPriceArray['decorative'];
			}
			else
			{
				$priceRange = $columnPriceArray['blank'];
			}
	    	foreach ($priceRange as $index=>$price) {
	    		if($qty < $price['to'])
	    		{
	    			return $price['rate'];
	    		}
	    		if (array_key_exists('to', $price) && isset($price['to']) && ($qty <= $price['to']) && ($qty >= $price['from'])) {
	    			return $price['rate'];
	    		}
	    	}
	    	$price = end($priceRange); 
	    	if ($price['from']<= $qty) {
	    		return $price['rate'];
	    	}
		//}
    	return false;
    }
    
    public function getLowestProductQty($columnPriceArray)
    {
    	if (array_key_exists('0', $columnPriceArray) && array_key_exists('from', $columnPriceArray['0'])) {
    		return $columnPriceArray['0']['from'];
    	}
    	return null;
    }
    
    public function isInteger($number)
    {
    	return ctype_digit((string) $number);
    }
    
    public function prepareFormJsonError($form)
    {
    	return array(
    		'form_name' => $form->getName(),
    		'form_status' => 'error',
    		'form_errors' => $this->formErrorManager->prepareErrorArray($this->validator->validate($form))
    	);
    }
    
    public function makeDir($dirBasePath, $downloadRelativePath)
    {	
    	shell_exec('chmod 0777 -R '.$downloadRelativePath.'/*');
    	if (!file_exists($dirBasePath)) {
	    	if (!mkdir($dirBasePath, 0777, true)) {
	    		die('Failed to create folder');
	    	}
    	}	
    	chmod($dirBasePath, 0777);
    } 
    
    public function saveUrlToFile($sourceUrl, $destinationPath, $destinationAbsoluteZipFolder)
    {	
    	if (!file_exists($destinationAbsoluteZipFolder)) {
    		try {
	   			$ch = curl_init();
	   			curl_setopt($ch, CURLOPT_URL, $sourceUrl);
	   			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   			$data = curl_exec ($ch);
	   			curl_close ($ch);
	   		}
	   		catch(Exception $e){
	   			throw new Exception("Invalid URL",0,$e);
	   		}
	   		$file = fopen($destinationPath, 'w+') or die('can not open file');
	   		chmod($destinationPath, 0777);
	   		fputs($file, $data);
	   		fclose($file);
    	}
    }
    
    public function checkFileExistOnRemoteServer($remoteUrl){
    	$f=@fopen($remoteUrl,"r");
    	if($f)
    	{
    		fclose($f);
    		return true;
    	}
    	return false;
    	
    }
}
