<?php

namespace AutoAdmin\Bundle\BrickBuilder\Command;

use AutoAdmin\Bundle\Core\Util\CaseConverter;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;

#[AsCommand(name: 'aa:brick-builder:create-brick-handler')]
class CreateBrickHandlerCommand extends Command
{
    private ContainerInterface $container;
    private Filesystem $filesystem;

    public function __construct(ContainerInterface $container, Filesystem $filesystem)
    {
        $this->container = $container;
        $this->filesystem = $filesystem;

        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setDescription('Create a new Brick.');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $helper = $this->getHelper('question');

        try {
            // create handler directory in app
            $projectDir = $this->container->getParameter('kernel.project_dir');
            $brickHandlerDir = $projectDir . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Brick' . DIRECTORY_SEPARATOR . 'Handler';
            $brickTemplateDir = $projectDir . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'brick';
            $this->filesystem->mkdir($brickHandlerDir);
            $this->filesystem->mkdir($brickTemplateDir);


            $classNamePrefix = $helper->ask(
                $input,
                $output,
                new Question('Enter brick handler class name (ex: TitleTextImage): ')
            );

            $cc = new CaseConverter();
            $brickTypeId = $cc->camelToSnakeCase($classNamePrefix);

            $brickTypeId = $helper->ask(
                $input,
                $output,
                new Question(
                    'Enter brick code (ex: title_text_image) or leave auto-generated:[' . $brickTypeId . ']:', $brickTypeId
                )
            );

            $sourcePath = __DIR__ . '/../../../resources/file_templates/brick/handler.php';
            $brickHandlerFile = $brickHandlerDir . DIRECTORY_SEPARATOR . $classNamePrefix . 'BrickHandler' . '.php';
            $replace = [
                '/*HANDLER_CLASS_NAME*/' => $classNamePrefix,
                '/*HANDLER_BRICK_ID*/' => $brickTypeId,
            ];
            $this->transferTemplate($sourcePath, $brickHandlerFile, $replace);
            $output->writeln('Created: ' . $brickHandlerFile);

            $sourceTemplatePath = __DIR__ . '/../../../resources/file_templates/brick/template.html.twig';
            $brickTemplateFile = $brickTemplateDir . DIRECTORY_SEPARATOR . $brickTypeId . '.html.twig';
            $this->transferTemplate($sourceTemplatePath, $brickTemplateFile);
            $output->writeln('Created: ' . $brickTemplateFile);
        } catch (Exception $e) {
            $output->writeln("<error>Error: " . $e->getMessage() . "</error>");

            return self::FAILURE;
        }

        $output->writeln("<info>Brick template created properly</info>");

        return self::SUCCESS;
    }

    private function transferTemplate($sourcePath, $destPath, array $replace = []): void
    {
        $this->filesystem->touch($destPath);

        $fileContent = file_get_contents($sourcePath);

        $fileContent = str_replace(array_keys($replace), array_values($replace), $fileContent);

        if ($handle = fopen($destPath, 'w')) {
            fwrite($handle, $fileContent);
            fclose($handle);
        }
    }
}
