<?php

namespace Opentalent\OtAdmin\Command;

use Opentalent\OtAdmin\Controller\ScanController;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * This CLI command performs a full scan on the Typo3 db
 *
 * @package Opentalent\OtAdmin\Command
 */
class ScanCommand extends Command
{
    /**
     * -- This method is expected by Typo3, do not rename ou remove --
     *
     * Allows to configure the command.
     * Allows to add a description, a help text, and / or define arguments.
     *
     */
    protected function configure()
    {
        $this
            ->setName("ot:scan")
            ->setDescription("Scan the typo3 DB")
            ->setHelp("This CLI command performs a full scan on the Typo3 db.")
            ->addOption(
                'report',
                'r',
                InputOption::VALUE_OPTIONAL,
                'Build an html report file with the given name.'
            );
    }

    /**
     * -- This method is expected by Typo3, do not rename ou remove --
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Exception
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        // instanciate twig loader
        $loader = new \Twig\Loader\FilesystemLoader(dirname(__FILE__) . '/../../templates');
        $twig = new \Twig\Environment($loader);

        // evaluate the report path
        $report_path = $input->getOption('report');
        if ($report_path == null) {
            $report_path = getcwd() . '/scan_report.html';
        } else {
            $info = pathinfo($report_path);
            if ($info['extension'] != 'html') {
                $report_path .= '.html';
            }
        }

        // perform the scan
        $scanController = GeneralUtility::makeInstance(ObjectManager::class)->get(ScanController::class);
        $scan = $scanController->scanAllAction(true);

        // render the twig template
        $template = $twig->load('scan_report.twig');

        $html_report = $template->render(['scan' => $scan]);

        $f = fopen($report_path, 'w+');
        try {
            fwrite($f, $html_report);
            $io->success(sprintf("Report file was created at: " . $report_path));
        } finally {
            fclose($f);
        }
    }

}
