<?php

namespace App\Command;

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

class DeploymentClassUpdateCommand extends AbstractCommand
{
	protected function configure()
	{
		$this
			->setName('deployment:class-update')
			->setDescription('Create, update or delete class based on its definition file')
			->addArgument(
				'name',
				InputArgument::REQUIRED,
				'Class name'
			)
			->addArgument(
				'id',
				InputArgument::OPTIONAL,
				'Class ID'
			)
			->addOption(
				'delete', 'd',
				InputOption::VALUE_NONE,
				'Delete'
			);
	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		$name = trim($input->getArgument('name'));
		$delete = $input->getOption('delete');
		try {
			$definitionPath = PIMCORE_PRIVATE_VAR.'/classes/definition_'.$name.'.php';
			if (!file_exists($definitionPath)) {
				throw new \Exception(sprintf('Class definition file %s not found.', $definitionPath));
			}
			$class = ClassDefinition::getByName($name);
			if ($delete) {
				$class->delete();
				$output->writeln(sprintf('Class %s deleted', $name));
			} else {
				if (!$class) {
					$id = trim($input->getArgument('id'));
					if (!$id) {
						throw new \Exception(sprintf('No ID provided for new class %s.', $definitionPath));
					}
					$generator = new Generator();
					$classId = $generator->createClassDefinition($name, false, false, null, $id, $definitionPath);
					if (!$classId) {
						throw new \Exception(sprintf(
							'Class %s [%d] could not be created. See %s for details.',
							$name,
							$id,
							'/var/log/generator.log'
						));
					}
					$output->writeln(sprintf('Class %s [%d] created', $name, $id));
				} else {
					$class->save();
					$output->writeln(sprintf('Class %s updated', $name));
				}
			}
		} catch (\Exception $e) {
			$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
		}
	}
}
