<?php 

namespace NPS\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use NPS\Repository\KnowledgeBaseRepository;
use NPS\Entity\KnowledgeBase;
use Doctrine\ORM\EntityManagerInterface;
use NPS\DependencyInjection\IKnowledgeBaseInfoProvider;
use NPS\Etc\Strings;
use NPS\Factory\KnowledgeBaseFactory;
use NPS\Factory\FileFactory;
use NPS\Repository\FileRepository;

/**
 * Uploads a (media) file
 * @author Lukas Korinek
 */
class UploadFileCommand extends Command
{

    /** @var FileFactory $factory */
    private $factory;

    /** @var FileRepository $repo */
    private $repo;

    /** @var EntityManagerInterface $em */
    private $em;

    public function __construct(EntityManagerInterface $em, FileFactory $factory, FileRepository $repo)
    {
        $this->factory = $factory;
        $this->repo = $repo;
        $this->em = $em;

        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this 
            ->setName('file:upload')
            ->setDescription('Uploads a (media) file')
            ->addArgument('path', InputArgument::REQUIRED)
            ->addOption('hidden', null, InputOption::VALUE_NONE, 'Should the file be stored in a non public directory?')
            ->addOption('note', null, InputOption::VALUE_REQUIRED, 'Note to the file')
            ->addOption('tags', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_REQUIRED, 'Tags which should be added', []);
    }   

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path');
        $tags = $input->getOption('tags');
        $note = $input->getOption('note') ? trim($input->getOption('note')) : null;
        $public = !$input->getOption('hidden');

        if($tags && !is_array($tags))
        {
            $tags = [$tags];
        }

        $file = $this->factory->createFromPath($this->repo->getNewId(), $path, null, $tags, $public, $note);
        $this->em->flush();

        $output->writeln('Created file "' . $file->getUrl() . '" with id ' . $file->getId());
        return 0;
    }
}


