<?php

namespace OfficeBrain\Bundle\AttributeBundle\Controller;

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 OfficeBrain\Bundle\CategoryBundle\Entity as Entity;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\HttpFoundation\StreamedResponse;
use PHPExcel;
use PHPExcel_IOFactory;

/**
*
* @Route("/admin/{_locale}/swatches")
*/

class SwatchesAdminController extends Controller
{
	public function __construct()
	{
		$this->statsh_cache_wrapper = RedisCacheService::create();
	}
	
	public function init()
	{
		$this->request = $this->getRequest();		
		$this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        if ($this->has('office_brain_queue_api_manager')) {
            $this->request->attributes->set('object', 'CultureAttribute');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
        
        list($this->default_languagge) = explode("_",$this->container->getParameter('locale'));
	}
	
	/**
	 * @Route("/list/{language}/{page}",
	 * name="officebrain_bundle_swatches_list",
	 * requirements={"records_per_page"="12|24|48|96|996"},
	 * defaults={"records_per_page"=10,"page"=1,"language"=""})
	 * @Template("OfficeBrainAttributeBundle:SwatchesAdmin:list.html.twig")
	 */

	public function listAction(){
		$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		$culture = ($param['language'])? $param['language'] : $this->default_languagge;
		$searchQuery = $this->request->get('search_query');
		$sortBy = $this->request->get('sort_by');
		$sortType = $this->request->get('sort_type');
		$searchBy = $this->request->get('search_by');		
		
		// For Pagination
		$page = $this->request->get('page', '1');
		$records_per_page = $param['records_per_page'];
		$start_index = (($page - 1) * $records_per_page);
		$attributeId=10;
		// Set Attrbute Value Limit For Listing	
		//$attribute_value_limit  = 10;
		if(! isset($param['culture'])){
			$param['culture']='';
		}
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$attrData = $api_manager->getAttributeSwatchesColor($attributeId,$start_index, $records_per_page,$culture,$searchBy, $searchQuery);
		if(count($attrData['api_data'])){
        $paginator = $this->get('knp_paginator');
        $data ['pagination'] = $paginator->paginate($attrData['all_data'], $page, $records_per_page, array(),count($attrData['all_data']));
        
        }
        $data['view_more_display'] = count($attrData['all_data']);
		$data['search_query'] = $searchQuery;
		$data['sort_by'] = $sortBy;
		$data['sort_type'] = $sortType;
		$data['attribute_data'] = $attrData['api_data'];
		$data['search_by'] = $searchBy;
		$data['activeCulture'] = $culture;
		$data['total_record'] =count($attrData['all_data']);
		$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
        return $data;
	}

    /*public function listAction()
    {
    	$this->init();
		$data['pagination']=array();
		$param = $this->request->get('_route_params');
		
		$culture = ($param['language'])? $param['language'] : $this->default_languagge;
		
		$searchQuery = $this->request->get('search_query');
		$sortBy = $this->request->get('sort_by');
		$sortType = $this->request->get('sort_type');
		$searchBy = $this->request->get('search_by');		
		
		// For Pagination
		$page = $this->request->get('page', '1');
		$records_per_page = $param['records_per_page'];
		$recordsPerPage = $this->request->query->get('recordsPerPage',10);
		$start_index = (($page - 1) * $recordsPerPage - 1);
		
		$swatchesColorId = $this->container->getParameter('swatches_color_id');
		//$swatchesColorId = array('10'); // Make it dynamic
		// End Pagination
				
		// Set Attrbute Value Limit For Listing
		$attribute_value_limit  = 10;
		if(! isset($param['culture'])){
			$param['culture']='';
		}
		$cultures = $this->container->getParameter('language');
		
		$this->moduleCachePrefix='__swatchManagement__';
		
		//$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('Swatchesvalue', $culture),$this->moduleCachePrefix);
        
		//$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
        //if($cacheData) {
        //	$swatches_val = $cacheData;
        //}else{
        	$api_manager = $this->get('officebrain_attribute_api_manager');
    		$swatches_val= $api_manager->getSwatchesList($culture,$swatchesColorId,1,array(),$searchQuery,$sortBy,$sortType,$records_per_page,$page,1,$attribute_value_limit);
    	//	RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$swatches_val);
        //}
        $colorAttributeId = 10;
		@list($attributeArrayData,$countArray) = $swatches_val;
    	$attribute_data= $attributeArrayData['data'];
    	$totalRecord = count($attributeArrayData['data_count'][$colorAttributeId]);
    	$all_attr_data = $attributeArrayData['data_count'][$colorAttributeId];
		if($searchQuery != ''){
			$searchQueryMatch = preg_quote($searchQuery, '/');
			$pattern = 	"/".$searchQueryMatch."/i";
			$items = array();
			if($searchBy == 'id'){
				$searchVal = 'attribute_value_id';
				$pattern = 	"/^".$searchQueryMatch."$/i";
			}else{
				$searchVal = 'attribute_value';
				$pattern = 	"/".$searchQueryMatch."/i";
			}
			$i = 0;
			foreach ($attribute_data as $attribute) {
			    if (preg_match($pattern, $attribute[$searchVal], $matches)){
			        $items[$i]['attribute_value'] = $attribute['attribute_value'];
			        $items[$i]['attribute_value_id'] = $attribute['attribute_value_id'];
			        $i++;
			    }    
			}
			if(!empty($items)){
				$attribute_data = $items;
			}else{
				$attribute_data = array();
			}
		}
		$data['view_more_display'] = $totalRecord;//$countArray;
		$data['search_query'] = $searchQuery;
		$data['sort_by'] = $sortBy;
		$data['sort_type'] = $sortType;
		$data['attribute_data'] = $attribute_data;
		$data['search_by'] = $searchBy;
		$data['activeCulture'] = $culture;
		$data['total_record'] = $totalRecord; //count($attribute_data);
		$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
		if ($totalRecord) {
            $paginator = $this->get('knp_paginator');
            $data ['pagination'] = $paginator->paginate($all_attr_data, $page, $records_per_page, array(), $totalRecord);
            
        }

        return $data;
				
	}*/
    
    /**
	 * @Route("/change/{swatches_id}",
	 * name="officebrain_bundle_attribute_swatches_changes",
	 * options={"expose"=true})
	 */
    
    public function swatchesChangeAction(){
    	
    	$this->init();
    	
    	$swatchsId = $this->request->get('swatches_id');
    	$product_api_manager = $this->get('office_brain_product_detail_manager');
    	
    	$status = $product_api_manager->uploadSwatches($swatchsId,$_FILES);
    	
    	if($status['status'] == 'error'){
    		return new JsonResponse(array('form_status' => 'error','error_message' => $status['msg'],'from' => 'swatches'));
    	}else{
    		return new JsonResponse(array('form_status' => 'success','success_message' => $status['msg'],'from' => 'swatches' ,'image_path' => $status['image_url'], 'swatche_id' => $swatchsId));
    	}
    	     	
    }
    
    /**
	 * @Route("/revert_swatches",
	 * name="officebrain_bundle_attribute_swatches_revert",
	 * options={"expose"=true})
	 */
    
    public function swatchesRevertAction(){
    	
    	$this->init();
    	
    	$swatchsId = $this->request->get('swatches_id');
    	$product_api_manager = $this->get('office_brain_product_detail_manager');
    	
    	$status = $product_api_manager->revertSwatches($swatchsId);
    	
    	return new JsonResponse(array('form_status' => 'success','success_message' => $status['msg'],'image_path' => $status['image_url']));
    	
    	     	
    }
    
    /**
   	 * @Route("/export_swatches",
   	 * name="officebrain_bundle_attribute_export_swatches",
   	 * options={"expose"=true})
   	 * @Template("")
   	 */
    public function exportSwatchesToCsvAction(){
    	$this->init();
    	ini_set('memory_limit', '-1');
    	$param = $this->request->get('_route_params');
		$culture = ($param['language'])? $param['language'] : $this->default_languagge;
		$api_manager = $this->get('officebrain_attribute_api_manager');
		$attributeId = 10;
		$swatches_val = $api_manager->getAttributeSwatchesColorExport($attributeId);
		    	$response = new Response();
    	$baseurl = $this->request->getScheme() . '://' . $this->request->getHttpHost() . $this->request->getBasePath();

    	$url = $this->request->getUri();
    	
        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("IDME")
                    ->setTitle("IDME Swatches")
                    ->setSubject("IDME Swatches");
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)        
                    ->setCellValue('A1', 'Swatch Id')
                    ->setCellValue('B1', 'Swatch Name')
                    ->setCellValue('C1', 'Path of the Swatch Image');
        // Set active sheet index to the first sheet
        foreach($swatches_val as $k => $res){
            $k = $k + 2;
            $filefound = '';
            $path = $this->container->getParameter('swatches_image.file_path').'/'.$res['attribute_value_id'].'.jpg';
            if (file_exists($path)) {   
				$filefound = $baseurl.'/product/color/'.$res['attribute_value_id'].'.jpg';
			}
            $objPHPExcel->setActiveSheetIndex(0)           
             		->setCellValue('A'.$k, $res['attribute_value_id'])
             		->setCellValue('B'.$k, $res['attribute_value'])
             		->setCellValue('c'.$k, $filefound);
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('c')->setWidth(80);


        // Redirect output to a client’s web browser (Excel5)
        $response->headers->set('Content-Type', 'application/vnd.ms-excel');
        $response->headers->set('Content-Disposition', 'attachment;filename="colour_swatches.xls"');
        $response->headers->set('Cache-Control', 'max-age=0');
        
        //$response->prepare();
        $response->sendHeaders();
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        
        exit();
    }

    /*public function exportSwatchesToCsvAction(){
    	
    	$this->init();
    	
    	$param = $this->request->get('_route_params');
		$culture = ($param['language'])? $param['language'] : $this->default_languagge;
        $this->moduleCachePrefix='__swatchManagement__';
		$cacheKey=RedisCacheService::generateKey($this->statsh_cache_wrapper,array('Swatchesvalue', $culture),$this->moduleCachePrefix);
        
		$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
        if($cacheData) {
        	$swatches_val = $cacheData;
        }else{
        	$api_manager = $this->get('officebrain_attribute_api_manager');
    		$swatches_val= $api_manager->getSwatchesList($culture,$swatchesColorId,1,array(),$searchQuery,$sortBy,$sortType,$records_per_page,$page,1,$attribute_value_limit);
    		RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$swatches_val);
        }

        $api_manager = $this->get('officebrain_attribute_api_manager');
    		$swatches_val= $api_manager->getSwatchesList($culture,$swatchesColorId,1,array(),$searchQuery,$sortBy,$sortType,$records_per_page,$page,1,$attribute_value_limit);
    	
    	$response = new Response();
    	$baseurl = $this->request->getScheme() . '://' . $this->request->getHttpHost() . $this->request->getBasePath();

    	$url = $this->request->getUri();
    	
        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("IDME")
                    ->setTitle("IDME Swatches")
                    ->setSubject("IDME Swatches");
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)        
                    ->setCellValue('A1', 'Swatch Id')
                    ->setCellValue('B1', 'Swatch Name')
                    ->setCellValue('C1', 'Path of the Swatch Image');
        // Set active sheet index to the first sheet
        foreach($swatches_val[0] as $k => $res){
                    $k = $k + 2;
            $objPHPExcel->setActiveSheetIndex(0)           
             		->setCellValue('A'.$k, $res['attribute_value_id'])
             		->setCellValue('B'.$k, $res['attribute_value'])
             		->setCellValue('c'.$k, $baseurl.'/product/color/'.$res['attribute_value_id'].'.jpg');
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('c')->setWidth(80);


        // Redirect output to a client’s web browser (Excel5)
        $response->headers->set('Content-Type', 'application/vnd.ms-excel');
        $response->headers->set('Content-Disposition', 'attachment;filename="colour_swatches.xls"');
        $response->headers->set('Cache-Control', 'max-age=0');
        
        //$response->prepare();
        $response->sendHeaders();
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        
        exit();
    }*/
    
    /**
     * @Route("/rename_swatches",
     * name="officebrain_bundle_attribute_rename_swatches",
     * options={"expose"=true})
     * @Template("OfficeBrainAttributeBundle:SwatchesAdmin:renameSwatches.html.twig")
     */
    
    public function renameSwatchesAction(){
    	$this->init();
    	
    	$param = $this->request->get('_route_params');
    	$culture = ($param['language'])? $param['language'] : $this->default_languagge;
    	$attribute_id = 10;
    	 
    	$swatchId = $this->request->get('swatchId');
    	$swatchName = $this->request->get('swatchName');
    	return array('activeCulture' => $culture, 'attribute_id' => $attribute_id, 'swatchId' => $swatchId, 'swatchName' => $swatchName);
    }

}
