<?php
namespace App\Controller;

use App\Entity\Import;
use App\Form\Type\ImportFormType;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\UserManipulator;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\Response;

class ImportController extends CRUDController
{
    public function listAction()
    {
        $import = new Import();
        $import->setUser($this->getUser());
        $form = $this->createForm(ImportFormType::class, $import);
        $form->handleRequest($this->getRequest());

        if ($form->isSubmitted() && $form->isValid()) {
            $import = $form->getData();
            $media = $import->getMedia();
            $provider = $this->getProvider($media);

            $this->em->persist($import);
            $this->em->flush();

            // TODO : finir import data from file
            $data = $this->parseCSV($provider->generatePath($media), $media->getProviderReference());

            $batchSize = 20;
            $cptLigne = 1;
            $errors = [];
            // Processing on each row of data
            foreach ($data as $row) {
                // @TODO
            }

            if (empty($errors)) {
                $import->setEnabled(true);
                $this->em->persist($import);
                $this->em->flush();
                $this->addFlash(
                    'success',
                    'Import effectué avec succès !'
                );
                $referer = $this->getRequest()->headers->get('referer');
                if ($referer && !$this->getRequest()->isXmlHttpRequest()) {
                    return $this->redirect($referer);
                } elseif (!$this->getRequest()->isXmlHttpRequest()) {
                    return new Response('', Response::HTTP_BAD_REQUEST);
                }
            } else {
                $this->addFlash(
                    'error',
                    'Import effectué avec succès !'
                );
            }
        }
        return $this->renderWithExtraParams('admin/import.html.twig', array(
            'action' => 'list',
            'form' => $form->createView()
        ));
    }

    private function parseCSV($filePath, $fileName, $ignoreFirstLine = false)
    {
        $finder = new Finder();
        $finder->files()
            ->in($filePath)
            ->name($fileName)
        ;
        foreach ($finder as $file) { $csv = $file; }

        $rows = array();
        if (($handle = fopen($csv->getRealPath(), "r")) !== FALSE) {
            $i = 0;
            while (($data = fgetcsv($handle, null, ";")) !== FALSE) {
                $i++;
                if ($ignoreFirstLine && $i == 1) { continue; }
                $rows[] = $data;
            }
            fclose($handle);
        }

        return $rows;
    }
}
