<?php namespace Builder\Users;

use Cartalyst\Sentry;
use Silex\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class UsersController {

	/**
	 * Request instance.
	 * 
	 * @var Symfony\Component\HttpFoundation\Request
	 */
	private $request;

	/**
	 * Paramater bag instance.
	 * 
	 * @var Symfony\Component\HttpFoundation\ParameterBag
	 */
	private $input;

	private $app;

	/**
	 * Create new ProjectsController instance.
	 * 
	 * @param Application $app    
	 * @param Request     $request
	 */
	public function __construct($app, Request $request, $sentry, $validator)
	{	
		$this->app = $app;
		$this->sentry = $sentry;
		$this->request = $request;
		$this->validator = $validator;
		$this->input = $request->request;
	}

	public function login()
	{
		$creds = $this->input->all();

		//do some basic validation just in case
		if ($this->validator->fails($creds, 'login')) {
			return new Response(json_encode($this->validator->errors), 400);
		}

		$error = [];

		try {
			$user = $this->sentry->authenticate($creds, true);
		}
		catch (\Cartalyst\Sentry\Users\WrongPasswordException $e) {
		    $error['*'] = $this->app['translator']->trans('wrongEmailOrPassword');
		}
		catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
		    $error['*'] = $this->app['translator']->trans('wrongEmailOrPassword');
		}
		catch (\Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
		    $error['*'] = $this->app['translator']->trans('userSuspended');
		}
		catch (\Cartalyst\Sentry\Throttling\UserBannedException $e) {
		    $error['*'] = $this->app['translator']->trans('userBanned');
		}

		if (count($error)) {
			return new Response(json_encode($error), 400);
		}

		$response = new Response($user, 200);
		$response->headers->setCookie(new Cookie('blUser', $user, 0, '/', null, false, false));

		return $response;
	}

	/**
	 * Register a new user.
	 * 
	 * @return Response
	 */
	public function store()
	{
		$creds = $this->input->all();

		if ($this->validator->fails($creds, 'register')) {
			return new Response(json_encode($this->validator->errors), 400);
		}

		try {
		    $this->input->remove('repeatPassword');
			$this->sentry->register($this->input->all(), true);
			$user = $this->sentry->authenticate($this->input->all(), true);
		} catch (\Cartalyst\Sentry\Users\UserExistsException $e) {
		    return new Response(json_encode(array('*' => $this->app['translator']->trans('emailTaken'))), 400);
		}

		$response = new Response($user, 201);
		$response->headers->setCookie(new Cookie('blUser', $user, 0, '/', null, false, false));

		return $response;
	}

	public function logout()
	{
		$this->sentry->logout();

		return new Response('', 200);
	}
}