<?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 GeneratorDocumentPageCreateCommand extends AbstractCommand
{
	protected function configure()
	{
		$this
			->setName('generator:document-page-create')
			->setDescription('Create a pimcore page document')
			->addArgument(
				'title',
				InputArgument::REQUIRED,
				'Page title (will also be used as page key and nagivation title)'
			)
			->addArgument(
				'controller',
				InputArgument::OPTIONAL,
				'Controller name in CamelCase without the Controller suffix',
				'Cms'
			)
			->addArgument(
				'action',
				InputArgument::OPTIONAL,
				'Action name in CamelCase without the Action suffix',
				'TemplateSimple'
			)
			->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(
				'parent', 'p',
				InputOption::VALUE_REQUIRED,
				'Parent document real full path or ID'
			)
			->addOption(
				'master', 'm',
				InputOption::VALUE_REQUIRED,
				'Master document real full path or ID'
			);
	}

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

		$title = ucfirst($input->getArgument('title'));
		$controller = ucfirst($input->getArgument('controller'));
		$action = ucfirst($input->getArgument('action'));
		$template = $input->getOption('template');
		if ($template) {
			$template = $generator->normalizePathParam($template);
		}
		$formHandler = $input->getOption('formhandler');
		if ($formHandler) {
			ucfirst($formHandler);
		}
		$parent = $input->getOption('parent');
		$master = $input->getOption('master');

		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>Page [%s] could not be created. See var/log/generator.log for details.</error>',
					$title
				));

				return false;
			}
		}
		$document = $generator->createDocumentPage(
			$title,
			$controller,
			$action,
			$parent,
			$template,
			$formHandler,
			$master
		);
		if ($document) {
			$output->writeln(sprintf('Document [%s] created with ID [%d]',
				$document->getRealFullPath(),
				$document->getId()
			));
			return AbstractCommand::SUCCESS;
		} else {
			$output->writeln('<error>Document page could not be created. See var/log/generator.log for details.</error>');
			return AbstractCommand::FAILURE;
		}
	}
}
