<?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\User;
use OfficeBrain\Bundle\UserBundle\Form\UserType;
use OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;

/**
 * @author Employee Id: 410175
 * OB eCommerce Product - SignUp
 * - SignUp Process for user
 * @Route("/api/v1", defaults={"_format" = "json"})
 */
class ApiSignUpController extends SignUpController
{
	const SUCCESS = 'success';
	const ERROR = 'error';
	const SUCCESS_CODE = 1;
	const ERROR_CODE = 0;
    /**
     * @author Employee Id: 410175
     *
     * To set member variables default value
     */
    public function __construct()
    {
        parent::__construct();
        $this->coreManager = null;
    }

    /**
     * @author Employee Id: 410175
     *
     *         To unset member variables
     */
    public function __destruct()
    {
        parent::__destruct();
        unset($this->coreManager);
    }

    /**
     * @author Employee Id: 410175
     *
     *         Create various objects required action in this class
     */
    public function initAction()
    {
        parent::initAction();
        $this->coreManager = $this->get('office_brain_core_manager');
        $this->oAuth = $this->get('ob_oauth.controller.token');
    }

   
    /**
     * @author Employee Id: 410175
     * OB eCommerce Product - SignUp
     * Function created to get signup Form Fields and validation list
     *
     * @Route("/{_locale}/get-register-form-fields",
     * 	name="office_brain_userbundle_sign_up_get_register_form_field_api" )
     *
     * @ApiDoc(
     *      resource=true,
     *      section="Core",
     *      description="To get Register Form Field Setting.",
     *      requirements={
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instanceId"},
     *      	{"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instanceType"},
     *          {"name"="_locale", "dataType"="string", "default"="en_us"}	,      	
     *      	{"name"="userType", "dataType"="string", "description"="end_user|supplier|distributor"}   ,
     *
     *      },
     *      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 getRegisterFormFieldAction()
    {
    	$this->initAction();
    	$userType = $this->request->get ( 'userType', null );
    	if($userType==null){
    		return array(
    				'status' => SELF::ERROR,
    				'status_code' => SELF::ERROR_CODE,
    				'message' => 'enter userType',
    		);
    	}
    	$signUpFormFields = $this->signUpManager->getsignUpFormDataArrayFormat ( $userType );
    	return array(
						'status' => SELF::SUCCESS,
						'status_code' => SELF::SUCCESS_CODE,
						'response_data' => $signUpFormFields,
				);
    }
    
    /**
     * @author Employee Id: 410175
     * OB eCommerce Product - SignUp
     * Function created to validate sign up form
     *
     * @Route("/{_locale}/register",
     * 	name="office_brain_userbundle_sign_up_register_post_api" )
     * 
     * @ApiDoc(
     *      resource=true,
     *      section="User",
     *      description="To Submit Registered User Data.",
     *      requirements={      	
     *      	{"name"="access_token", "dataType"="string", "required"=true, "description"="valid access token"},
     *      	{"name"="instance_id", "dataType"="integer", "required"=true, "description"="valid instanceId"},
     *      	{"name"="instance_type", "dataType"="string", "required"=true, "description"="valid instanceType"},  
     *          {"name"="_locale", "dataType"="string", "default"="en_us"}	, 
     *      	{"name"="billing_address", "dataType"="integer", "description"="Set 1 if Billing Address is checked; dont set this variable if billin address is not selected"},
     *      	{"name"="shipping_address", "dataType"="integer", "description"="Set 2 if Shipping Address is checked; dont set this variable if shipping address is not selected"},
     *      	{"name"="userType", "dataType"="string", "description"="end_user|supplier|distributor"}   ,
     *      	
     *      },     
     *      input = {
     *      	"class" = "\OfficeBrain\Bundle\UserBundle\Form\ApiUserType"
     *      },
     *      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("OfficeBrainUserBundle:SignUp:register.html.twig")
     */
    public function registerPostAction()
    {
    	$this->initAction();
    	
    	$userType = $this->request->get ( 'userType', 'supplier' );
    	
    	// TODO# Need to put condition if given userType is allowed for current instanceType
    	
		$signUpFormFields = $this->signUpManager->getsignUpFormData ( $userType );
		
		unset($signUpFormFields ['fields'] ['captcha']); // we need to unset captcha as we are creating for mobileApi
		
		$user = new User ();
		$userTypeObj = new UserType ( $this->coreManager, $signUpFormFields, 'main_register' );
		
		$form = $this->createForm ( $userTypeObj, $user );
		$form->handleRequest ( $this->request );
		
		$userStatus = $this->signUpManager->registerUser ( $form );
		
		if ($userStatus) {
			$erp_flag = TRUE;
			$user_type = $userStatus->getUserType ();
			$is_individual = $userStatus->getIsIndividual ();
			if (($user_type == 'end_user' && $this->projectSetting ['instance_type'] == 'supplier') || ($is_individual == TRUE && $this->projectSetting ['instance_type'] == 'supplier')) {
				$erp_flag = FALSE;
			}
			$erpIntegration = $this->projectSetting ['configuration_rule'] ['erp_integration'];
			if ($erpIntegration && $erpIntegration ['userManagement'] == 1 && ! empty ( $this->queueApiManager ) && $userStatus->getuserCompany () && ($userStatus->getStatus () == "active" || $userStatus->getStatus () == "inactive") && $erp_flag == TRUE) {
				$this->queueApiManager->mapQueue ( "create", $userStatus );
			}
		
			//Save Billing Address	
			$billingAddressId = 1;
			$billingAddress = $this->signUpManager->addAddress ( $user, $billingAddressId );
			if ($erpIntegration && $erpIntegration ['userManagement'] == 1 && ! empty ( $this->queueApiManager ) && $userStatus->getuserCompany () && ($userStatus->getStatus () == "active" || $userStatus->getStatus () == "inactive") && $erp_flag == TRUE) {
				$this->request->attributes->set ( 'object', 'ContactBook' );
				$this->queueApiManager->mapQueue ( "create", $billingAddress );
			}
			
			//Save Shipping Address	
			$shippingAddressId = 2;
			$shippingAddress = $this->signUpManager->addAddress ( $user, $shippingAddressId );
			if ($erpIntegration && $erpIntegration ['userManagement'] == 1 && ! empty ( $this->queueApiManager ) && ($userStatus->getStatus () == "active" || $userStatus->getStatus () == "inactive") && $userStatus->getuserCompany () && $erp_flag == TRUE) {
				$this->request->attributes->set ( 'object', 'ContactBook' );
				$this->queueApiManager->mapQueue ( "create", $shippingAddress );
			}
						
			$this->signUpManager->sendEmail ( $form, $this->translator->trans ( 'user.register.mail.subject' ) );
					
			if ($this->signUpConfigrations ['option'] ['allow_login_after_signup'] == 1) {
				$loginInfo = null;
				$clientId = $this->request->get('client_id', null);
				$clientSecret = $this->request->get('client_secret', null);
				if ($clientId != null && $clientSecret != null) { // only do AutoLogin if client_id & client_secret is given
					$loginInfo = $this->doLogin($form->get('email')->getData(), $form->get('password') ['first']->getData());
					$loginInfo = json_decode($loginInfo->getContent(), true);
				}
				// TODO# need to confirm with 4074 about autoLogin
				if ($loginInfo != null) {
					return array(
							'status' => SELF::SUCCESS,
							'status_code' => SELF::SUCCESS_CODE,
							'message' => $this->translator->trans('user.register.success'),
							'login_data' => $loginInfo,
					);
				} else {
					return array(
							'status' => SELF::SUCCESS,
							'status_code' => SELF::SUCCESS_CODE,
							'message' => $this->translator->trans('user.register.success'),
					);
				}
			} else {
				return array(
						'status' => SELF::SUCCESS,
						'status_code' => SELF::SUCCESS_CODE,
						'message' => $this->translator->trans('user.register.success'),
				);
			}
		}
				
		// $error = (string)$form->getErrors(true,false);print_r($error );
		$aryErrors = $this->formErrorManager->prepareErrorArray($this->get('validator')->validate($form));
		if (count($aryErrors) <= 0) {
			foreach ($form->getErrors(true) as $key => $error) {
				$aryErrors ['other_error'] = $error->getMessage();
				break;
			}
		}else{
			foreach ($aryErrors as $errorField=>$errorMsg){
				if($errorField == ""){
					unset($aryErrors[""]);
					$aryErrors['other_error'] = $errorMsg;
					break;
				}
			}
		}
				
		return array(
				'status' => SELF::ERROR,
				'status_code' => SELF::ERROR_CODE,
				'message' => $aryErrors ,
		);			
    	
    }

    private function doLogin($email, $pwd)
    {
        $newRequest = $this->request;
        $newRequest->request->set('grant_type', 'password');
        $newRequest->request->set('username', $email);
        $newRequest->request->set('password', $pwd);

        return $this->oAuth->tokenAction($newRequest);
    }
}
