<?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 NPS\DependencyInjection\NPSBridge;
use NPS\Etc\Strings;
use NPS\Factory\KnowledgeBaseFactory;

/**
 * Converts an old NPS knowledge base into a new one
 * @author Lukas Korinek
 */
class ConvertBaseCommand extends Command
{

    /** @var NPSBridge $nps  */
    private $nps;

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

    public function __construct(NPSBridge $nps, KnowledgeBaseFactory $factory)
    {
        $this->nps = $nps;
        $this->factory = $factory;

        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this 
            ->setName('base:convert')
            ->setDescription('Converts .n32 knowledge base into a .nps knowledge base')
            ->addOption('force', 'f')
            ->addArgument('source', InputArgument::REQUIRED, 'Name of a base to convert')
            ->addArgument('destination', InputArgument::OPTIONAL, 'Target file for converted output. If not passed, the source will be used.');
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $source = $input->getArgument('source');
        $destination = $input->getArgument('destination') ?: Strings::replace('.n32', '.nps', $source);

        if(!Strings::ends('n32', $source)) // Relative path translation
        {
            $source = $this->factory->getKnowledgeBasesDirectory() . '/' . $source . '.n32';
            $destination = Strings::replace('.n32', '.nps', $source);
        }

        if($input->getOption('force') == false && file_exists($destination))
        {
            $output->writeln('Target file ' . $destination . ' already exists');
            return 1;
        }
        
        if($this->nps->convertBaseFormat($source, $destination))
        {
            $output->writeln(sprintf('%s converted successfully to %s', $source, $destination));
            return 0;
        }
        else 
        {
            $output->writeln(sprintf('Failed converting %s to %s', $source, $destination));
            return 2;
        }
    }
}

