<?php

namespace AdminBundle\Form\Handler;


use AdminBundle\Entity\Gallery;
use AdminBundle\Form\PictureForm;
use AdminBundle\Helper\GuidHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

class PictureFormHandler {

    /**
     * @var Form
     */
    protected $form;
    /**
     * @var Request
     */
    protected $request;
    /**
     * @var ContainerInterface
     */
    protected $container;

    function __construct(Form $form, Request $request, ContainerInterface $container)
    {
        $this->form = $form;
        $this->request = $request;
        $this->container = $container;
    }

    /**
     * Process the form
     *
     * @return bool
     */
    public function process() {
        if($this->request->isMethod('post')) {
            $data = $this->form->getData();
            $this->onSuccess($data);
            return true;
        }
        return false;
    }

    /**
     * @param PictureForm $data
     */
    protected function onSuccess($data) {
        $picture = new Gallery();
        $picture->setLabel($data->getLabel());

        $file = $data->getFile();
        $filename = GuidHelper::GUID() . '.' . $file->guessExtension();
        $output = __DIR__ . '/../../../../web/uploads/gallery/';
        $file->move($output, $filename);
        $picture->setPath('/uploads/gallery/' . $filename);

        $entityManager = $this->container->get('doctrine.orm.entity_manager');
        $entityManager->persist($picture);
        $entityManager->flush();
    }

}