<?php declare(strict_types=1);
/*
 * irstea/file-upload-bundle - Bundle de gestion de fichiers intégrée à Symfony et Twitter-Bootstrap.
 * Copyright (C) 2015-2020 Irstea <dsi.poleis.contact@lists.irstea.fr>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License and the GNU
 * Lesser General Public License along with this program. If not, see
 * <https://www.gnu.org/licenses/>.
 */

namespace Irstea\FileUploadBundle\Command;

use Doctrine\ORM\EntityManagerInterface;
use Irstea\FileUploadBundle\Model\FileManagerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Description of GarbageCollectorCommand.
 */
class CreateCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('irstea:file-upload:create')
            ->setDescription('Créer un fichier.')
            ->addOption('mime-type', 't', InputOption::VALUE_REQUIRED, 'Force le type MIME.')
            ->addOption('display-name', 'd', InputOption::VALUE_REQUIRED, 'Indique un nom de fichier.')
            ->addOption('metadata', 'm', InputOption::VALUE_REQUIRED, 'Ajoute des métadata (format JSON).')
            ->addArgument('path', InputArgument::REQUIRED, "Nom du fichier à ajouter, - pour lire l'entrée standard");
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var EntityManagerInterface $em */
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');

        $written = null;

        $em->transactional(
            function () use ($input, $em, &$file, &$written) {
                /** @var FileManagerInterface $manager */
                $manager = $this->getContainer()->get('irstea_file_upload.file_manager');

                $path = $input->getArgument('path');
                if ($path === '-') {
                    $realPath = 'php://stdin';
                    $displayName = 'stdin';
                    $lastModified = time();
                    $size = 0;
                } else {
                    $realPath = $path;
                    $displayName = pathinfo($path, PATHINFO_FILENAME);
                    $size = filesize($path);
                    $lastModified = filemtime($path);
                }

                $mimeType = $input->getOption('mime-type');
                $forcedDisplayName = $input->getOption('display-name');
                if (null !== $forcedDisplayName) {
                    $displayName = $forcedDisplayName;
                }
                $metadata = null;
                $jsonMetadata = $input->getOption('metadata');
                if ($jsonMetadata !== null) {
                    $metadata = json_decode($jsonMetadata);
                }

                $file = $manager->create($displayName, $size, $mimeType ?: 'application/octet-stream', $lastModified);

                $fh = fopen($realPath, 'rb');
                $written = $file->copyFrom($fh);
                fclose($fh);

                $manager->completed($file);

                if ($mimeType) {
                    $file->setMimeType($mimeType);
                }
                if ($metadata) {
                    $file->setMetadata(array_merge($file->getMetadata(), $metadata));
                }

                $em->flush();
            }
        );

        if ($output->isVerbose()) {
            $output->writeln(sprintf('%s crée, %d octets lus.', $file->getId(), $written));
        } else {
            $output->writeln($file->getId());
        }
    }
}