<?php

namespace MenulisAi\Pdfgen\Command;

use MenulisAi\Pdfgen\Document\Ebook;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class Generate extends Command
{
    protected static $defaultName = "generate";

    protected function configure()
    {
        $this->setDescription('Generate a PDF document file from JSON data')
            ->addArgument("input", InputArgument::REQUIRED, "Input path file JSON")
            ->addArgument("output", InputArgument::OPTIONAL, "Set the output path");
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $inPath = $input->getArgument("input");

        $doc = new Ebook($inPath);

        $path = $doc->compile();

        $cmd = new Process([
            "soffice",
            "--headless",
            "--convert-to",
            "pdf",
            "--outdir",
            "storage/",
            $path
        ]);

        $cmd->run();

        if (!$cmd->isSuccessful()) {
            throw new ProcessFailedException($cmd);
        }

        $output->writeln($cmd->getOutput());

        return Command::SUCCESS;
    }
}
