<?php

namespace Comitium5\DesignerBundle\Form\Manager;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Class UniqueFormManager
 *
 * Joan Pont <joan.pont@bab-soft.com>
 * @package Comitium5\DesignerBundle\Form\Manager
 */
class UniqueFormManager
{
    /**
     *
     */
    const NAMESPACE_KEY = 'forms';

    /**
     * @var Session
     */
    private $session;

    /**
     * @var string
     */
    private $fieldName;


    /**
     * UniqueFormManager constructor.
     * @param Session|null $session
     * @param null $fieldName
     */
    public function __construct(Session $session = null, $fieldName = null)
    {
        $this->session = $session;
        $this->fieldName = $fieldName;
    }

    /**
     * @param Form $form
     * @param $name
     * @return bool
     */
    public function has(Form $form, $name)
    {
        return $this->session->has($this->getKey($form, $name));
    }

    /**
     * @param Form $form
     * @param $name
     * @param null $default
     * @return mixed
     */
    public function get(Form $form, $name, $default = null)
    {
        return $this->session->get($this->getKey($form, $name), $default);
    }

    /**
     * @param Form $form
     * @param $name
     * @param $value
     */
    public function set(Form $form, $name, $value)
    {
        $this->session->set($this->getKey($form, $name), $value);
    }

    /**
     * @param $key
     * @param $value
     */
    public function setWithKey($key, $value)
    {
        $this->session->set($key, $value);
    }

    /**
     * @param Form $form
     * @param $name
     */
    public function remove(Form $form, $name)
    {
        $this->session->remove($this->getKey($form, $name));
    }


    /**
     * @return mixed
     */
    public function all()
    {
        return $this->session->get(self::NAMESPACE_KEY);
    }

    /**
     * @param Form $form
     * @param $name
     * @return string
     */
    public function getKey(Form $form, $name)
    {
        if (!$form->has($this->fieldName)) {
            return;
        }

        return $this->getFQDN($form->get($this->fieldName)->getData(), $name);
    }

    /**
     * @param $formId
     * @param $name
     * @return string
     */
    public function getFQDN($formId, $name)
    {
        return self::NAMESPACE_KEY."/{$formId}/{$name}";
    }

    /**
     * @return Session
     */
    public function getSession()
    {
        return $this->session;
    }
}