<?php

namespace AppBundle\Form\Extension;

use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;

class SecureFileTypeExtension extends AbstractTypeExtension
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var \UserInterface
     */
    private $user;

    
    public function __construct(
        RouterInterface $router,
        UserInterface $user
    )
    {
        $this->router = $router;
        $this->user = $user;
    }
    
    
    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return FileType::class;
    }

    /**
     * Add the image_path option
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined([
            'secure_file_name',
            'secure_file_owner'
        ]);
    }

    /**
     * Pass the image url to the view
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (!empty($options['secure_file_name'])) {
            $parentData = $form->getParent()->getData();

            $fileName = null;

            if (null !== $parentData) {
                $accessor = PropertyAccess::createPropertyAccessor();
                $fileName = $accessor->getValue($parentData, $options['secure_file_name']);
            }

            $fileOwner = !empty($options['secure_file_owner']) ? $options['secure_file_owner'] : $this->user->getId();

            if (!empty($fileName) && !empty($fileOwner)) {
                $view->vars['absolute_url'] = $this->router->generate('secure_user_file', ['filename' => $fileName, 'ownerId' => $fileOwner]);
            }
        }
    }
}
