<?php

namespace AppBundle\Command;

use AppBundle\Entity\Media;
use AppBundle\Enum\MediaType;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;

/**
 * Update the filenames of the Content 'article' property according to the medias filenames.
 * @author Bastien Gatellier <contact@bgatellier.fr>
 */
class UpdateContentPathCommand extends ContainerAwareCommand
{
    /**
     * 
     */
    protected function configure()
    {
        $this
            ->setName('cgenial:update-path:content')
            ->setDescription("Update the media path of every content.");
    }

    /**
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get("doctrine.orm.entity_manager");

        $media = new Media();
        $media->setPath('');
        $media->setType(MediaType::PDF);

        $finder = new Finder();
        $finder->files()->in($media->getAbsolutePath());

        // Create a new progress bar
        $progress = new ProgressBar($output, $finder->count());

        // Start and displays the progress bar
        $progress->start();

        foreach ($finder as $file) {
            $filename = $file->getFilename();

            // Extract the unique identifier from the filename.
            // This identifier will be the key between the filename on the filesystem
            // and the filename from the database.
            $uniqueId = substr($filename, 0, strpos($filename, '-'));

            // Check that $uniqueId has a sha1 format (40 hexadecimal characters)
            if (preg_match('/^[0-9a-f]{40}$/i', $uniqueId)) {
                $extension = substr($filename, strrpos($filename, '.') + 1);

                // Grab every Content that contains this unique identifier in his 'article' property
                $qb = $em->createQueryBuilder();
                $qb
                    ->select('c')
                    ->from('AppBundle:Content', 'c')
                    ->where($qb->expr()->like('c.article', ':cArticle'))
                    ->setParameter('cArticle', "%$uniqueId-%")
                ;
                $contents = $qb->getQuery()->getResult();

                // Replace the filename from the 'article' property by the name of the file on the filesystem
                foreach ($contents as $c) {
                    $articleUpdated = preg_replace('/'.$uniqueId.'-.*\.'.$extension.'/', $filename, $c->getArticle());

                    $c->setArticle($articleUpdated);

                    $em->merge($c);
                }
            }

            $progress->advance();
        }

        $em->flush();

        // Ensure that the progress bar is at 100%
        $progress->finish();
    }
}
