<?php
namespace Sso\WebserviceBundle\Security\Api\Firewall\Level;

use Sso\WebserviceBundle\Security\Api\Manager as ApiManager;
use Sso\WebserviceBundle\Security\Exception\FirewallException;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Factory
 * @package Sso\WebserviceBundle\Security\Api\Validation
 */
class One
{
    const CONTROLLER = 'API-CONTROLLER';
    const ACTION = 'API-ACTION';

    /**
     * @var ApiManager
     */
    private $apiM;

    /**
     * @var \Sso\WebserviceBundle\ErrorHandler\ErrorStorage\Factory
     */
    private $errorStorage;

    /**
     * Factory constructor.
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $this->errorStorage = $this->apiM->getErrorHandler()->errorStorage();
    }

    /**
     * @param Request $request
     * @return bool
     * @throws FirewallException
     */
    public function headerValidation(Request $request)
    {

        if (!$request->headers->get(static::CONTROLLER)) {
            $this->errorStorage->setErrorFromValues(404, 'fw001', 'hd001', 'Invalid controller', 'Header API-CONTROLLER not found.');
        } else {
            //ok we have the controller which the errorStorage want to know
            $this->errorStorage->setController($request->headers->get(static::CONTROLLER));
            $this->apiM->getServiceCommand()->setController($request->headers->get(static::CONTROLLER));
        }

        if (!$request->headers->get(static::ACTION)) {
            $this->errorStorage->setErrorFromValues(404, 'fw001', 'hd002', 'Invalid action', 'Header API-ACTION not found.');
        } else {
            //ok we have the action which the errorStorage want to know
            $this->errorStorage->setAction($request->headers->get(static::ACTION));
            $this->apiM->getServiceCommand()->setAction($request->headers->get(static::ACTION));
        }

        if($this->errorStorage->hasErrors()){

            throw new FirewallException('Firewall Level One Exception');
        }

        return true;
    }
}
