<?php

namespace OfficeBrain\Bundle\UserBundle\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\UserBundle\Entity\ContactBook;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\UserBundle\Form\ContactBookType;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * @author Employee Id: 410175
 * OB eCommerce Product - Contact Book Api
 * @Route("/api/v1", defaults={"_format" = "json"})
 */
class ApiContactBookController extends ContactBookController
{
	const SUCCESS = 'success';
	const ERROR = 'error';
	const SUCCESS_CODE = 1;
	const ERROR_CODE = 0;
    /**
     *
     * @author Employee Id: 410175
     *	set default value
     *
     * @return NULL
     */
    public function __construct()
    {
    	parent::__construct();   
    }
    
    /**
     *
     * @author Employee Id: 410175
     *		 To unset value
     *
     * @return NULL
     */
    public function __destruct()
    {
    	parent::__destruct();
    }
    
    /**
     *
     * @author Employee Id: 410175
     *		Create objects which use this class
     *
     * @return NULL
     */
    public function initAction()
    {
    	parent::initAction ();
    }
    
    /**
     * @author Employee Id: 410175
     *
     * @Route("/{_locale}/get-contact-book-address-type", name="office_brain_userbundle_contactbook_address_type_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="Get Address Type for Address Book",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *       	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *       	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      },
     *      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 getAddressTypeAction()
    {
    	$this->initAction ();
		return array (
				'status' => SELF::SUCCESS,
				'status_code' => SELF::SUCCESS_CODE,
				'response_data' => $this->contactbookmanager->getAddressTypeMobileApi () 
		);
    }
    
    /**
     * @author Employee Id: 410175
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("/{_locale}/my-account/address-book/add", name="office_brain_userbundle_contactbook_addcontactbookpost_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To add Address Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      },     
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\UserBundle\Form\ApiAddressBookType"
     *      },
     *      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({"POST"})
     *  @Template()
     */
    
    public function addContactBookPostAction()
    {
        $this->initAction ();
		
        $this->form = $this->createForm(new ContactBookType($this->container), new ContactBook());
        $this->form ->handleRequest($this->request);
        if ($this->form->isValid()) {
            $contactBookData = $this->form->getData();
            $add=$this->contactbookmanager->addContactBook($contactBookData, '', 1);
            
            if ($add ['status'] == 'SUCCESS') {
            	if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
            		$this->queueApiManager->mapQueue("create", $add['data']);
            	}
            	
            	return array (
            			'status' => SELF::SUCCESS,
            			'status_code' => SELF::SUCCESS_CODE,
            			'message' => $this->translator->trans('user.contact_book.add_message.address_success')
            	);
            	
            }else{
            	return array (
            			'status' => SELF::ERROR,
            			'status_code' => SELF::ERROR_CODE,
            			'message' => $this->translator->trans ( 'user.contact_book.add_message.address_fail' )
            	);
            }           
        }

        $errorsMsg = '';
        foreach ( $this->get ( 'validator' )->validate ( $this->form ) as $error ) {
        	$errorsMsg = $error->getMessage ();
        	break;
        }
        return array (
        		'status' => SELF::ERROR,
        		'status_code' => SELF::ERROR_CODE,
        		'message' => $errorsMsg
        );     
    } 
    
    

    /**
     * @author Employee Id: 410175
     * OB eCommerce Product -  contact book View
     *
     * @Route("/{_locale}/my-account/address-book/view",name="office_brain_userbundle_contactbook_viewcontactbook_api")
     *
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To View Address Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="page", "dataType"="integer", "description"="page number"},
     *      	{"name"="records_per_page", "dataType"="integer", "description"="record per page"},
     *      	{"name"="address_type", "dataType"="integer", "description"="address type id"}
     *      },
     *      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 viewContactBookAction()
     {
     	$this->initAction ();
    		
		$contactBookData = $this->contactbookmanager->getContactBookMobileApi ( $this->userId, $this->addressBookFlag, $this->page, $this->recordsPerPage );
		
		$responseData = array ();
		$responseData ['items'] = $contactBookData->getItems ();
		if (count ( $responseData ['items'] ) <= 0)
			$responseData ['items'] = null;
		$responseData ['pagination'] = $contactBookData->getPaginationData ();
		
		return array (
				'status' => SELF::SUCCESS,
				'status_code' => SELF::SUCCESS_CODE,
				'response_data' => $responseData 
		);
    }
    
	/**
     * @author Employee Id: 410175
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("/{_locale}/my-account/address-book/edit/{contactBookId}", name="office_brain_userbundle_contactbook_editcontactbookpost_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To Edit Address Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="contactBookId", "dataType"="integer", "description"="existing Address id"}
     *      },     
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\UserBundle\Form\ApiAddressBookType"
     *      },
     *      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({"POST"})
     * @Template()
     */
    
    public function editContactBookPostAction()
    {   
    	
    	$this->initAction();
    	$contactBookId = $this->request->get('contactBookId');
    	$contactBookObject = $this->contactbookmanager->getSingleContactBook($contactBookId);
    	
    	if($contactBookObject && $this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->addressBookConfigrationField['allowed_users']))
    	{
    		$previousAddressType=$contactBookObject->getAdressType()->getId();
    		$this->form  = $this->createForm(new ContactBookType($this->container), $contactBookObject);
    		$this->form ->handleRequest($this->request);
    		if ($this->form->isValid()) {
    			$contactBookData = $this->form->getData();
    			if($previousAddressType!=$contactBookData->getAdressType()->getId()) {
    				$this->changeAddressTypeFlag=1;
    			}
    			$edit = $this->contactbookmanager->editContactBook($contactBookData,$this->changeAddressTypeFlag);
    			
    			if($edit['status'] == 'SUCCESS' ){
    				if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
    					if($edit['data']->getErpId()){
    						$this->queueApiManager->mapQueue("update", $edit['data']);
    					}else{
    						$this->queueApiManager->mapQueue("create", $edit['data']);
    					}
    				}    				
    				return array (
    						'status' => SELF::SUCCESS,
    						'status_code' => SELF::SUCCESS_CODE,
    						'message' => $this->translator->trans('user.contact_book.edit_message.address_success')
    				);
    			}else{
    				return array (
    						'status' => SELF::ERROR,
    						'status_code' => SELF::ERROR_CODE,
    						'message' =>  $this->translator->trans('user.contact_book.edit_message.address_fail')
    				);
    			}
    		}  	
    	
    		$errorsMsg = '';
    		foreach ( $this->get ( 'validator' )->validate ( $this->form ) as $error ) {
    			$errorsMsg = $error->getMessage ();
    			break;
    		}
    		return array (
    				'status' => SELF::ERROR,
    				'status_code' => SELF::ERROR_CODE,
    				'message' => $errorsMsg
    		);
    		
    	}else {
    		$this->exceptionManager->throwAccessException();
    	}    	
    }
   
    
	/**
     * @author Employee Id: 410175
     * OB eCommerce Product -  contact book Delete
     *
     * @Route("/{_locale}/my-account/address-book/delete", name="office_brain_userbundle_contactbook_deletecontactbook_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To Delete Address Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="contactBookId", "dataType"="integer", "description"="existing Address id"}
     *      },
     *      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({"POST"})
     * @Template()
     */
    
    public function deleteContactBookAction()
    {
    	
    	$this->initAction();
    	$contactBookArray = $this->contactbookmanager->getSingleContactBook($this->contactBookId);
    	
    	if($contactBookArray && $this->exceptionManager->isUserAllowedToAccess($contactBookArray->getCreatedUid(), $this->addressBookConfigrationField['allowed_users']))
    	{
    		$contactBook = $this->contactbookmanager->deleteContactBook($this->contactBookId);
    		
    		if($contactBook['status'] == 'SUCCESS'){
    			if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
    				$this->queueApiManager->mapQueue("remove", array('id' => $this->contactBookId));
    			}
    			return array (
    					'status' => SELF::SUCCESS,
    					'status_code' => SELF::SUCCESS_CODE,
    					'message' => $this->get('translator')->trans('user.contact_book.remove_message.address_success')
    			);
    		}else{
    			return array (
    					'status' => SELF::ERROR,
    					'status_code' => SELF::ERROR_CODE,
    					'message' => $this->translator->trans('user.contact_book.remove_message.address_fail')
    			);
    		}   		
    	}else {
    		$this->exceptionManager->throwAccessException();
    	}
       
    }
    
	/**
     * @author Employee Id: 410175
     * OB eCommerce Product -  contact book View
     *
     * @Route("/{_locale}/my-account/address-book/view/{contactBookId}", name="office_brain_userbundle_contactbook_getdatacontactbook_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To View Address Book Data by AddressBookId.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="contactBookId", "dataType"="integer", "description"="existing Address id"}
     *      },
     *      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 getDataContactBookAction()
    {
        $this->initAction ();
				
		if ($this->contactBookId == null || $this->contactBookId <= 0) {
			return array (
					'status' => SELF::ERROR,
					'status_code' => SELF::ERROR_CODE,
					'message' => $this->translator->trans ( 'user.contact_book.view_message.no_contact_msg' ) 
			);
		}
		
		$contactBook = $this->contactbookmanager->getSingleContactBookMobileApi ( $this->contactBookId);
		
		if ($contactBook) {
			return array (
					'status' => SELF::SUCCESS,
					'status_code' => SELF::SUCCESS_CODE,
					'response_data' => $contactBook 
			);
		} else {
			return array (
					'status' => SELF::ERROR,
					'status_code' => SELF::ERROR_CODE,
					'message' => $this->translator->trans ( 'user.contact_book.view_message.no_contact_msg' ) 
			);
		} 
    }
    
    /**
     * @author Employee Id: 410175 -
     * OB eCommerce Product -  Contact Book
     *
     * @Route("/{_locale}/my-account/address-book/get-default-address", name="office_brain_userbundle_contactbook_getdefaultaddress_api")
     *
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To get default Address Book id for shipping and|or billing.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      },
     *      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("POST")
     */
    public function getDefaultAddressAction()
    {
    	$this->initAction ();
		
		$defaultContactBook = $this->contactbookmanager->getDefaultContactBookIdMobileApi ( $this->userId );
		
		if (is_array ( $defaultContactBook ) && count ( $defaultContactBook ) > 0) {
			return array (
					'status' => SELF::SUCCESS,
					'status_code' => SELF::SUCCESS_CODE,
					'response_data' => $defaultContactBook 
			);
		}
		return array (
				'status' => SELF::ERROR,
				'status_code' => SELF::ERROR_CODE,
				'message' => $this->translator->trans ( 'front.ecatalog.default_address.not_found' ) 
		);
    }
    
    /**
     * @author Employee Id: 410175
     * OB eCommerce Product -  Is Default Update
     *
     * @Route("{_locale}/my-account/address-book/is-default",
     * 	name="office_brain_userbundle_contactbook_isdefault_api" )
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Address Book",
     *      description="To set default address for Address Book.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *          {"name"="id", "dataType"="integer", "description"="existing Address id"}
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template()
     * @Method("GET")
     */
    
    public function isDefaultAction()
    {
    	$this->initAction();
    	$data = array();
    	$contactBookId = $this->request->get('id');
    	$isDefault = $this->contactbookmanager->updateIsDefault($contactBookId);
    	
    	if( 'SUCCESS' == $isDefault['status'] ) {
    		if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
    			if($isDefault['data']->getErpId()){
    				$this->queueApiManager->mapQueue("update", $isDefault['data']);
    			}else{
    				$this->queueApiManager->mapQueue("create", $isDefault['data']);
    			}
    		}
    		
    		return array (
    				'status' => SELF::SUCCESS,
    				'status_code' => SELF::SUCCESS_CODE,
    				'message' =>  $this->translator->trans('user.contact_book.update_default.address_success')
    		);
    	}
    	
    	return array (
    			'status' => SELF::ERROR,
    			'status_code' => SELF::ERROR_CODE,
    			'message' => $this->translator->trans('user.contact_book.update_default.address_fail')
    	);
    }
    
    
    
    
     /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("/{_locale}/my-account/mycontact-book/add/{userId}", name="office_brain_userbundle_mycontactbook_addcontactbookpost_api",defaults={"userId"=0})
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="To Add Contact Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *          {"name"="userId", "dataType"="integer", "default"="0"},
     *      },     
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\UserBundle\Form\ApiContactBookType"
     *      },
     *      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({"POST"})
     * @Template()
     */
    
    public function addMyContactBookPostAction()
    {
    	$this->initActionMyContactBook();
    	$contactBook = new ContactBook();
    	
    	if($this->requestUserId==0 || $this->requestUserId == '' || $this->requestUserId == null){
    		$this->requestUserId = $this->userId;
    		$user = $this->user;
    	}else{
    		$user = $this->contactbookmanager->getValidUserById($this->requestUserId);
    	}
    	if ($user and $user != '') {
    		$contactBook->setUser($user);
    	}
    
    	$contactBookObj = new ContactBookType($this->container, $this->dashboardFlag);
    	$this->form = $this->createForm($contactBookObj, $contactBook);
    	$this->form ->handleRequest($this->request);
    	if ($this->form->isValid()) {
    		$contactBookData = $this->form->getData();
    		$add=$this->contactbookmanager->addContactBook($contactBookData, $this->dashboardFlag, $this->contactBookFlag);
    		
    		if( 'SUCCESS' == $add['status'] ) {
    			$userId = $add['data']->getUser()->getId();
    			if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)) {
    				if ($user->getUserType() != 'end_user' && !empty($user->getUserCompany())) {
    					$this->queueApiManager->mapQueue("create", $add['data']);
    				} else if ($user->getUserType() == 'end_user') {
    					$this->queueApiManager->mapQueue("create", $add['data']);
    				}
    			}
    			
    			return array (
    					'status' => SELF::SUCCESS,
    					'status_code' => SELF::SUCCESS_CODE,
    					'message' =>  $this->translator->trans('user.contact_book.add_message.success_msg')
    			);
    		} else {
    			return array (
    					'status' => SELF::ERROR,
    					'status_code' => SELF::ERROR_CODE,
    					'message' => $this->translator->trans('user.contact_book.add_message.fail_msg')
    			);
    		}
    		
    	}
    	
    	$errorsMsg = '';
    	foreach ( $this->get ( 'validator' )->validate ( $this->form ) as $error ) {
    		$errorsMsg = $error->getMessage ();
    		break;
    	}
    	return array (
    			'status' => SELF::ERROR,
    			'status_code' => SELF::ERROR_CODE,
    			'message' => $errorsMsg
    	);
    	
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book View
     *
     * @Route("/{_locale}/my-account/mycontact-book/view/{userId}",name="office_brain_userbundle_mycontactbook_viewcontactbook_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="Get All Contact Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *          {"name"="userId", "dataType"="integer", "default"="0"},
     *          {"name"="page", "dataType"="integer", "description"="page number"},
     *      	{"name"="records_per_page", "dataType"="integer", "description"="record per page"},
     *      	{"name"="address_type", "dataType"="integer", "description"="address type id"}
     *      },
     *      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 viewMyContactBookAction()
    {    	
    	$this->initActionMyContactBook();
    	if($this->requestUserId==0 || $this->requestUserId == '' || $this->requestUserId == null){ $this->requestUserId = $this->userId; }
    	$this->prepareSearchParameterArray();
    	
    	$contactBookData = $this->contactbookmanager->getContactBookMobileApi ( $this->requestUserId, $this->contactBookFlag, $this->page, $this->recordsPerPage, $this->searchParameterArray);
    	
    	$contactData = array ();
    	$contactData ['items'] = $contactBookData->getItems ();
    	if (count ( $contactData ['items'] ) <= 0)
    		$contactData ['items'] = null;
    	$contactData ['pagination'] = $contactBookData->getPaginationData ();
    	
    	return array (
				'status' => SELF::SUCCESS,
				'status_code' => SELF::SUCCESS_CODE,
				'response_data' => $contactData 
		);
    }
    
    
    /**
     * @author : 4493)
     * OB eCommerce Product - get sindle record of Contact Book
     * @Route("/{_locale}/my-account/mycontact-book/view/popup/{id}",name="office_brain_userbundle_mycontactbook_viewcontactbookpopup_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="To View Contact Book Data by ContactBookId.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="id", "dataType"="integer", "description"="existing Contactbook id"}
     *      },
     *      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 viewMyContactBookPopupAction()
    {
    	$this->initActionMyContactBook();
 	   	$contactBook = $this->contactbookmanager->getSingleContactBookMobileApi($this->contactBookId);
    	
    	if($contactBook && $this->exceptionManager->isUserAllowedToAccess($contactBook['createdUid'], $this->contactBookConfigurationField['allowed_users']))
    	{
    		
    		if ($contactBook) {
    			return array (
    					'status' => SELF::SUCCESS,
    					'status_code' => SELF::SUCCESS_CODE,
    					'response_data' => $contactBook
    			);
    		} else {
    			return array (
    					'status' => SELF::ERROR,
    					'status_code' => SELF::ERROR_CODE,
    					'message' => $this->translator->trans ( 'user.contact_book.view_message.no_contact_msg' )
    			);
    		}
    		
    	}else {
    		$this->exceptionManager->throwAccessException();
    	}    
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  contact book form submit
     *
     * @Route("/{_locale}/my-account/mycontact-book/edit/{contactBookId}", name="office_brain_userbundle_mycontactbook_editcontactbookpost_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="To Edit Contact Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="contactBookId", "dataType"="integer", "description"="existing ContactBook id"}
     *      },     
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\UserBundle\Form\ApiContactBookType"
     *      },
     *      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({"POST"})
     * @Template()
     */
    
    public function editMyContactBookPostAction()
    {
    	$this->initActionMyContactBook();
    	$contactBookId = $this->request->get('contactBookId');
    	$contactBookObject = $this->contactbookmanager->getSingleContactBook($contactBookId);
    
    
    	if($contactBookObject && $this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
    	{
    		$userId = $contactBookObject->getUser()->getId();
    		if($userId == $this->userId){
    			$this->dashboardFlag = 'myContactBook';
    			$user = $this->user;
    		}else{
    			$user = $this->contactbookmanager->getValidUserById($userId);
    		}
    		$previousAddressType=$contactBookObject->getAdressType()->getId();
    		$this->form  = $this->createForm(new ContactBookType($this->container, $this->dashboardFlag), $contactBookObject);
    		$this->form ->handleRequest($this->request);
    
    		if ($this->form->isValid()) {
    			$contactBookData = $this->form->getData();
    			if($previousAddressType!=$contactBookData->getAdressType()->getId()) {
    				$this->changeAddressTypeFlag=1;
    			}
    			$add = $this->contactbookmanager->editContactBook($contactBookData,$this->changeAddressTypeFlag);
    			
    			if( 'SUCCESS' ==  $add['status'] ) {
    				if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager)){
    					if ($user->getUserType() != 'end_user' && !empty($user->getUserCompany())) {
    						if ($add['data']->getErpId() > 0) {
    							$this->queueApiManager->mapQueue("update", $add['data']);
    						} else {
    							$this->queueApiManager->mapQueue("create", $add['data']);
    						}
    					} else if ($user->getUserType() == 'end_user') {
    						if ($add['data']->getErpId() > 0) {
    							$this->queueApiManager->mapQueue("update", $add['data']);
    						} else {
    							$this->queueApiManager->mapQueue("create", $add['data']);
    						}
    					}
    				}
    				return array (
    						'status' => SELF::SUCCESS,
    						'status_code' => SELF::SUCCESS_CODE,
    						'message' => $this->translator->trans('user.contact_book.edit_message.success_msg')
    				);
    			} else {
    				return array (
		    				'status' => SELF::ERROR,
		    				'status_code' => SELF::ERROR_CODE,
		    				'message' => $this->translator->trans('user.contact_book.edit_message.fail_msg')
		    		);
    			}
    			
    		}
    
    		$errorsMsg = '';
    		foreach ( $this->get ( 'validator' )->validate ( $this->form ) as $error ) {
    			$errorsMsg = $error->getMessage ();
    			break;
    		}
    		return array (
    				'status' => SELF::ERROR,
    				'status_code' => SELF::ERROR_CODE,
    				'message' => $errorsMsg
    		);
    
    	}else {
    		$this->exceptionManager->throwAccessException();
    	}
    
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -   contact book Delete
     *
     * @Route("/{_locale}/my-account/mycontact-book/delete", name="office_brain_userbundle_mycontactbook_deletecontactbook_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="To Delete Contact Book Data.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "description"="en_us", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *      	{"name"="id", "dataType"="integer", "description"="existing Address id"}
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template()
     * @Method("POST")
     */
    public function deleteMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$contactBookObject = $this->contactbookmanager->getSingleContactBook($this->contactBookId);
    
    	if($contactBookObject && $this->exceptionManager->isUserAllowedToAccess($contactBookObject->getCreatedUid(), $this->contactBookConfigurationField['allowed_users']))
    	{    		 
    		$userId = $contactBookObject->getUser()->getId();
    		$erpId = $contactBookObject->getErpId();
    		$contactBook = $this->contactbookmanager->deleteContactBook($this->contactBookId);
    
    		if( 'SUCCESS' == $contactBook['status'] ) {
    			if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) && $erpId > 0) {
    				$this->queueApiManager->mapQueue("remove", array('id' => $this->contactBookId, 'erp_id' => $erpId));
    			}
    			return array (
    					'status' => SELF::SUCCESS,
    					'status_code' => SELF::SUCCESS_CODE,
    					'message' => $this->get('translator')->trans('user.contact_book.remove_message.success_msg')
    			);
    		} else {
    			return array (
    					'status' => SELF::ERROR,
    					'status_code' => SELF::ERROR_CODE,
    					'message' =>  $this->get('translator')->trans('user.contact_book.remove_message.fail_msg')
    			);
    		}
    
    	}else {
    		$this->exceptionManager->throwAccessException();
    	}
    
    }
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product -  Is Default Update
     *
     * @Route("/{_locale}/my-account/mycontact-book/is-default", name="office_brain_userbundle_mycontactbook_isdefault_api")
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="Contact Book",
     *      description="To set default contact for ContactBook.",
     *      requirements={
     *      	{"name"="_locale", "dataType"="string", "default"="en_us"},
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instance_id"},
     *          {"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instance_type"},
     *          {"name"="id", "dataType"="integer", "description"="existing ContactBook id"}
     *      },
     *      statusCodes={
     *              1="Returned when success",
     *              403="Returned when the user is not authorized to see this link",
     *              0="Returned when form validation is failed",
     *      }
     * )
     * 
     * @Template()
     * @Method("GET")
     */
    
    public function isDefaultActionMyContactBookAction()
    {
    	$this->initActionMyContactBook();
    	$data = array();
    	$contactBookId = $this->request->get('id');
    	$isDefault = $this->contactbookmanager->updateIsDefault($contactBookId);
    	
    	if ( 'SUCCESS' == $isDefault['status'] ) {
    		if ($this->erpIntegration && $this->erpIntegration['userManagement'] == 1 && !empty($this->queueApiManager) ) {
    			if($isDefault['data']->getErpId()){
    				$this->queueApiManager->mapQueue("update", $isDefault['data']);
    			}else{
    				$this->queueApiManager->mapQueue("create", $isDefault['data']);
    			}
    		}
    		return array (
    				'status' => SELF::SUCCESS,
    				'status_code' => SELF::SUCCESS_CODE,
    				'message' => $this->get('translator')->trans('user.contact_book.update_default.success_msg')
    		);
    	} else {
    		return array (
    				'status' => SELF::ERROR,
    				'status_code' => SELF::ERROR_CODE,
    				'message' => $this->get('translator')->trans('user.contact_book.update_default.fail_msg')
    		);
    	}    	
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - preapre  search parameter
     */
    private function prepareSearchParameterArray()
    {
    	$this->searchParameterArray[$this->request->get('option', null)]=trim($this->request->get('keywords', null));
    }
    
}