<?php

namespace Sso\WebserviceBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Sso\WebserviceBundle\Error\Storage as ErrorStorage;
use Sso\WebserviceBundle\Error\Type\External as ExternalError;

class WsValidateListener implements EventSubscriberInterface
{

    /**
     *
     * @var ErrorStorage
     */
    protected $errors;

    public function __construct(ErrorStorage $errorStorage)
    {
        $this->errors = $errorStorage;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $request = $event->getRequest();
        if (!$configuration = $request->attributes->get('_wsValidate')) {
            return;
        }

        foreach ($configuration->getValidations() as $validation) {
            $method = 'validate' . $validation;
            $this->$method($event);
        }
    }

    public static function getSubscribedEvents()
    {
        return array(KernelEvents::CONTROLLER => ['onKernelController', -1]);
    }

    protected function validateHeader(FilterControllerEvent $event)
    {
        $request = $event->getRequest();
        $header = $request->headers;

        if (!$header->has('api-controller')) {
            $this->errors->addError(new ExternalError('h11', 'ControllerNotFound', 'Header API-CONTROLLER not found.'));
        } elseif (false === ($this->_apiControllerName = filter_var($header->get('api-controller'), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH))) {
            $this->errors->addError(new ExternalError('h12', 'ControllerNotFound', 'Header API-CONTROLLER not found.'));
        } elseif ($event->getController()) {

        }
        $c = $event->getController();
        var_dump(get_class_methods($c[0]));

        if (!$header->has('api-action')) {
            $this->errors->addError(new ExternalError('h13', 'ActionNotFound', 'Header API-ACTION not found.'));
        } elseif (false === ($this->_apiActionName = filter_var($header->get('api-action'), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH))) {
            $this->errors->addError(new ExternalError('h14', 'ActionNotFound', 'Header API-ACTION not found.'));
        }
    }

    protected function validateXml(FilterControllerEvent $event)
    {

    }

}
