<?php

namespace OfficeBrain\Bundle\SearchBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;

/**
 * Mobiel API Browse Category.
 *
 * @author Employee Id: 410175
 *        
 *         Desciption: This is a Browse Category controler returns Category
 *        
 * @param
 *        	NULL
 *        	
 * @return Html Response
 *               
 * @throws null @Route("/api/v1")
 */
class ApiBrowseCategoryController extends BrowseCategoryController
{
    protected $request;
    protected $catList;
    /**
     * @author Employee Id: 410175
     *        
     *         To set member variables default value
     */
    public function __construct()
    {
        parent::__construct();

        $this->searchManager = null;
    }

    /**
     * @author Employee Id: 40175
     *        
     *         Create various objects required action in this class
     */
    public function initAction()
    {
        parent::initAction();

        $this->request = $this->getRequest();
        $this->projectSetting = $this->request->get('project_setting');
        $this->userId = $this->projectSetting ['user_id'];
        $this->catList = null;
        $this->allChildCatList = null;

        $this->translator = $this->get('translator');
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->wishListManager = $this->get('office_brain_wish_list_manager');

        $this->baseUrl = $this->container->getParameter('base_url');
    }

    /*
     * @author Employee Id: 40175
     *        
     *         Browse by category
     *        
     * @param
     *        	string category slug
     *        	
     * @return if result found return parent category else null
     *             
     * @Route("/{_locale}/browse-category", name="office_brain_search_bundle_browse_category_api")
     *             
     * @ApiDoc(
     *            resource=true,
     *            section="Product-Category",
     *            description="Return to Browse Category",
     *            input = {
     *         		   "class" = "\OfficeBrain\Bundle\UserBundle\Form\ProductSearchData"
     *            },
     *            requirements={
     *            		{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *            		{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *            },
     *            statusCodes={
     *            		1="Returned when success",
     *            		403="Returned when the user is not authorized to see this link",
     *            		0="Returned when form validation is failed",
     *            }
     *         )
     * @Method({"GET"})
     *             
     * @Template()
     * /
    public function browseCategoryAction()
    {
        $this->initAction();

        $categoryData = parent::browseCategoryAction();

        $this->setCategoryVariableToCount($categoryData ['parent_category_list']);
        $newCat ['parent_category_list'] = $this->removeCategoryIDFromKey($categoryData ['parent_category_list']);

        if (is_array($newCat)) {
            return array(
                    'status' => 'success',
                    'status_code' => 1,
                    'data' => $newCat,
            );
        }

        return $newCat;
    }

    private function setCategoryVariableToCount($category)
    {
        $this->setAllCategoryToCount($category);

        $formData = new ProductSearchData($this->entityManager);
        $formData->setCategoryId(array_keys($this->allChildCatList));
        $formData->setSort(array(
                'field' => 'price',
                'order' => 'asc',
        ));

        $searchFilter = $this->searchManager->searchFilter($formData);

        foreach ($searchFilter ['categoryNameId'] as $key => $catCount) {
            if (isset($catCount ['id']) && $catCount ['count'] > 0) {
                $this->allChildCatList [$catCount ['id']] = $catCount ['count'];
            }
        }
    }

    private function setAllCategoryToCount($category)
    {
        foreach ($category as $key => $cat) {
            $this->allChildCatList [$cat ['local_id']] = 0;
            if (isset($cat ['child']) && is_array($cat ['child'])) {
                $category [$key] ['child'] = $this->setAllCategoryToCount($cat ['child']);
            }
        }
    }

    private function removeCategoryIDFromKey($category, $allLevelAllow = false)
    {
        foreach ($category as $key => $cat) {
            //$category [$key] ['product_image'] = ((isset($cat ['image']) && $cat ['image'] != '') ? $this->baseUrl.'/images/uploads/category/'.$cat ['image'] : $this->baseUrl.'images/accessories.png');
        	$category [$key] ['product_image'] = ((isset($cat ['image']) && $cat ['image'] != '') ? $this->baseUrl.'/images/uploads/category/thumbnail/'.$cat ['image'] : $this->baseUrl.'images/accessories.png');
            $category [$key] ['product_count'] = (isset($this->allChildCatList [$cat ['local_id']]) ? $this->allChildCatList [$cat ['local_id']] : 0);
            if (isset($cat ['child']) && is_array($cat ['child'])) {
                if ($allLevelAllow == true) {
                    unset($category [$key] ['child']);
                } else {
                    $category [$key] ['child'] = $this->removeCategoryIDFromKey($cat ['child']);
                }
            }
        }
        $this->catList = array_values($category);

        return $this->catList;
    }

    /**
     * @author Employee Id: 40175
     *        
     *         Browse by sub category
     *        
     * @param
     *        	string category slug
     *        	
     * @return if result found return sub category list else null
     *             
     * @Route("/{_locale}/browse-sub-category/{category_slug}", name="office_brain_search_bundle_browse_sub_category_api", options={"expose"=true})
     *             
     * @ApiDoc(
     *            resource=true,
     *            section="Product-Category",
     *            description="Return to Browse Sub Category",
     *            input = {
     *            		"class" = "\OfficeBrain\Bundle\UserBundle\Form\ProductSearchData"
     *            },
     *            requirements={
     *           		 {"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *            		{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *            },
     *            statusCodes={
     *            		1="Returned when success",
     *           		 403="Returned when the user is not authorized to see this link",
     *           		 0="Returned when form validation is failed",
     *            }
     *       )
     * @Method({"GET"})
     *             
     * @Template()
     * /
    public function browseSubCategoryAction()
    {
        $this->initAction();
        $categoryData = parent::browseSubCategoryAction();

        if (isset($categoryData ['sub_category_list']) && count($categoryData ['sub_category_list']) > 0) {
            $this->setCategoryVariableToCount($categoryData ['sub_category_list']);
            $newSubCat ['sub_category_list'] = $this->removeCategoryIDFromKey($categoryData ['sub_category_list'], $onlyNextLevel = false);
        } else {
            return array(
                    'status' => 'error',
                    'status_code' => 0,
                    'message' => $this->translator->trans('no_subcategory_found'),
            );
        }

        if (is_array($newSubCat)) {
            return array(
                    'status' => 'success',
                    'status_code' => 1,
                    'data' => $newSubCat,
            );
        }

        return $newSubCat;
    }

    /**
     * @author Employee Id: 410175
     *        
     *         Product listing accordingly parent category
     *        
     * @param
     *        	string category id
     *        	
     * @return if result found return category products else null
     *             
     * @Route("/{_locale}/category-product-list/{category_slug}", name="office_brain_search_bundle_category_product_list_api")
     *             
     * @ApiDoc(
     *            resource=true,
     *            section="Product List",
     *            description="Get Product Data By Category.",
     *            requirements={
     *           	 {"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *           	 {"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *            	{"name"="page", "dataType"="integer", "description"="Page number from 1", "default"="1"},
     *           	 {"name"="per_page", "dataType"="integer", "description"="total Number of record per page"}
     *            },
     *            statusCodes={
     *            	1="Returned when success",
     *            	403="Returned when the user is not authorized to see this link",
     *            	0="Returned when form validation is failed",
     *            }
     *        )
     *             
     * @Method({"GET"})
     *             
     * @Template()
     * /
    public function categoryProductListAction()
    {
        $this->initAction();

        $wishListProducts = array();
        if ($this->userId > 0) {
            $this->wishListManager->getWishListId();
            $wishListProducts = $this->wishListManager->productIdArray;
        }

        $categoryProducts = parent::categoryProductListAction();

        $newCategoryProducts = $categoryProducts;
        if (isset($newCategoryProducts ['form'])) {
            unset($newCategoryProducts ['form']);
        }
        if (isset($newCategoryProducts ['search_query'])) {
            unset($newCategoryProducts ['search_query']);
        }
        if (isset($newCategoryProducts ['Recent_search'])) {
            unset($newCategoryProducts ['Recent_search']);
        }
        if (isset($newCategoryProducts ['save_search'])) {
            unset($newCategoryProducts ['save_search']);
        }

        $newCategoryProducts = $newCategoryProducts ['search_result_array'];
        $newCategoryProducts ['category_breadcrumb'] = $categoryProducts ['category_breadcrumb'];
        $newCategoryProducts ['category_slug'] = $categoryProducts ['category_slug'];
        $newCategoryProducts ['category_id'] = $categoryProducts ['category_id'];

        if (isset($newCategoryProducts ['data']) && count($newCategoryProducts ['data']) == 0) {
            $newCategoryProducts ['data'] = null;
        } else {
            foreach ($newCategoryProducts ['data'] as $dataKey => $prodData) {
                if (in_array($prodData ['product_id'], $wishListProducts)) {
                    $newCategoryProducts ['data'] [$dataKey] ['is_wishlist_product'] = 1;
                } else {
                    $newCategoryProducts ['data'] [$dataKey] ['is_wishlist_product'] = 0;
                }
            }
        }

        return array(
                'status' => 'success',
                'status_code' => 1,
                'data' => $newCategoryProducts,
        );
    }*/
}
