<?php


namespace AutoAdmin\Bundle\Admin\Controller\Admin;

use AutoAdmin\Bundle\Admin\Exception\ForbiddenActionException;
use AutoAdmin\Bundle\Admin\Exception\UnknownEntityException;
use AutoAdmin\Bundle\Admin\Form\ImportRedirectType;
use AutoAdmin\Bundle\Admin\Helper\FlashbagHelper;
use AutoAdmin\Bundle\Content\Service\DuplicatorService;
use AutoAdmin\Bundle\Seo\Entity\Redirect;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

/**
 * Class EntityController
 * @package AutoAdmin\Bundle\Admin\Controller\Admin
 *
 */
class RedirectController extends EntityController
{
    /**
     * @param string $entitySlug
     * @param Request $request
     * @return RedirectResponse|Response
     * @throws ForbiddenActionException
     * @throws UnknownEntityException
     */
    public function import(string $entitySlug, Request $request)
    {
        $this->ensureActionIsAllowed($entitySlug, 'import');
        $form = $this->createForm(ImportRedirectType::class, null, [
            'help' => $this->adminRouter->generate($entitySlug, 'templateFile')
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var UploadedFile $file */
            $file = $form->get('file')->getData();

            if ($file) {
                foreach (explode("\n", $file->getContent()) as $key => $row) {
                    $data = explode(";", $row);

                    if (($key === 0 && $form->get('skip_first_line')->getData()) || count($data) !== 3) {
                        continue;
                    }

                    $class = $this->entityHelper->findFullClassName($entitySlug);
                    /** @var Redirect $entity */
                    $redirect = $this->contentFactory->createEntity($class);

                    $redirect->setOrigin($data[0]);
                    $redirect->setDestination($data[1]);
                    $redirect->setType((int)$data[2]);

                    $this->entityManager->persist($redirect);
                }

                $this->entityManager->flush();
                FlashbagHelper::addSuccess($request, 'Import des redirections terminé');

                return $this->redirectToRoute('aa_admin_entity', [
                    'entitySlug' => $entitySlug,
                    'action' => 'list',
                ]);
            }
        }

        return $this->render(
            '@AutoAdminAdmin/redirect/import.html.twig',
            [
                'form' => $form->createView(),
            ]
        );
    }

    public function templateFile()
    {
        $response = new BinaryFileResponse(__DIR__ . '/../../Resources/documents/redirect-import-template.csv');
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'fichier-exemple.csv');
        return $response;
    }

}
