<?php

namespace App\Command;

use App\Service\Generator;
use Pimcore\Console\AbstractCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GeneratorControllerActionCreateCommand extends AbstractCommand
{
	protected function configure()
	{
		$this
			->setName('generator:controller-action-create')
			->setDescription('Create a symfony action inside a controller')
			->addArgument(
				'name',
				InputArgument::REQUIRED,
				'Action name in CamelCase without the Action suffix'
			)
			->addArgument(
				'controller',
				InputArgument::OPTIONAL,
				'Controller name in CamelCase without the Controller suffix',
				'Cms'
			)
			->addOption(
				'template', 't',
				InputOption::VALUE_REQUIRED,
				'Path to a template file which will be used as a view script'
			)
			->addOption(
				'formhandler', 'f',
				InputOption::VALUE_REQUIRED,
				'Form name in CamelCase without Form suffix to create a form handler too'
			)
			->addOption(
				'document', 'd',
				InputOption::VALUE_REQUIRED,
				'Real full path to a document which will be added to action annotation comment'
			)
			->addOption(
				'noview', null,
				InputOption::VALUE_NONE,
				'Do not create view script (option is ignored if a template path is passed)',
				null
			);
	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		$generator = new Generator();

		$name = ucfirst($input->getArgument('name'));
		$controller = ucfirst($input->getArgument('controller'));
		$formHandler = $input->getOption('formhandler');
		$documentPath = $input->getOption('document');
		if ($formHandler) {
			ucfirst($formHandler);
		}
		$template = $input->getOption('template');
		if ($template) {
			$template = $generator->normalizePathParam($template);
		}
		$noView = $input->getOption('noview');

		if ($formHandler) {
			$handlerName = $generator->createFormHandler($formHandler, $controller);
			if ($handlerName) {
				$output->writeln(sprintf(
					'Form handler [%s] created in [%sController]',
					$handlerName,
					$controller
				));
			} else {
				$output->writeln(sprintf(
					'<error>Action [%s] could not be created. See var/log/generator.log for details.</error>',
					$name
				));

				return false;
			}
		}

		if ($generator->createAction($name, $controller, $formHandler, ($template) ? $template : !$noView, $documentPath)) {
			$output->writeln(sprintf(
				'Action [%sAction] created in [%sController]',
				$name,
				$controller
			));
			return AbstractCommand::SUCCESS;
		} else {
			$output->writeln(sprintf(
				'<error>Action [%sAction] could no be created in [%sController]. See var/log/generator.log for details.</error>',
				$name,
				$controller
			));
			return AbstractCommand::FAILURE;
		}
	}
}
