<?php
/**
 * ParamProvider using Query
 * 
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\ManagementBundle\AdminList\Param;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * ParamProvider using Query
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class QueryParamProvider implements ParamProviderInterface
{
    /**
     * Option Name
     * @var string
     */
    private $option;
    
    /**
     * Session
     * @var SessionInterface
     */
    private $session;
    
    /**
     * SessionKey
     * @var string
     */
    private $sessionKey;

    /**
     * Default value
     * @var string Default
     */
    private $default;
    
    /**
     * Constructor
     * 
     * @param string           $option     Option name
     * @param SessionInterface $session    Session
     * @param string           $sessionkey Session Key
     * @param string           $default    Default value
     */
    function __construct($option, SessionInterface $session = null, $sessionKey = null, $default = '')
    {
        $this->option = $option;
        $this->session = $session;
        $this->sessionKey = $sessionKey;
        $this->default = $default;
    }
    
    /**
     * {@inheritdoc}
     */
    public function process(Request $request, array &$params, array &$options) {
        
        // If we want to use an Session but we have no key create one
        if (($this->session !== null) AND ($this->sessionKey === null)) {
            $this->sessionKey = sha1($request->getPathInfo() . $this->option);
        }

        if ($this->session !== null) {
            $default = $this->session->get($this->sessionKey, $this->default);
        } else {
            $default = $this->default;
        }        

        if ('' !== ($value = $request->query->get($this->option, $default))) {
            $params[$this->option] = $value;
            if (($this->option != 'page') AND ($this->option != 'orderBy') AND ($this->option != 'orderDir')) {
                $options[$this->option] = $value;
            }                        
        }
        
        if ($this->session !== null) {
            $this->session->set($this->sessionKey, $value);
        }
        
    }
    
}