<?php

namespace Opentalent\OtAdmin\Command;


use Opentalent\OtAdmin\Controller\SiteController;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
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\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * This CLI command updates the routing index for the given website
 *
 * @package Opentalent\OtAdmin\Command
 */
class UpdateRoutingIndexCommand 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:site:index")
            ->setDescription("Update the routes index for the given website(s)")
            ->setHelp("This CLI command updates the routing index for the given website")
            ->addOption(
                'all',
                null,
                InputOption::VALUE_NONE,
                "Update all of the organization websites"
            )
            ->addArgument(
                'organization-id',
                InputArgument::OPTIONAL,
                "The organization's id in the opentalent DB"
            );
    }

    /**
     * -- 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)
    {
        $org_id = $input->getArgument('organization-id');
        $all = $input->getOption('all');

        if ($all && $org_id) {
            throw new \InvalidArgumentException("You can not pass both an organization id and the --all option");
        }
        if (!$all && !$org_id) {
            throw new \InvalidArgumentException("You shall either pass an organization id or use the --all option");
        }

        $io = new SymfonyStyle($input, $output);

        $siteController = GeneralUtility::makeInstance(ObjectManager::class)->get(SiteController::class);

        if ($all) {
            $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
            $queryBuilder = $connectionPool->getQueryBuilderForTable('pages');
            $sites = $queryBuilder
                ->select('tx_opentalent_structure_id')
                ->from('pages')
                ->where('is_siteroot=1')
                ->andWhere($queryBuilder->expr()->gt('tx_opentalent_structure_id', 0))
                ->execute()
                ->fetchAll();

            $io->progressStart(count($sites));

            foreach ($sites as $site) {
                $org_id = $site['tx_opentalent_structure_id'];
                try {
                    $siteController->updateRoutingIndexAction($org_id);
                } catch (\Throwable $e) {
                    $io->error('Organization Id: ' . $org_id . ' - ' . $e->getMessage());
                }
                $io->progressAdvance(1);
            }
            $io->progressFinish();

            $io->success(sprintf("The routing index has all been fully updated"));
        } else {
            $rootUid = $siteController->updateRoutingIndexAction($org_id);
            $io->success(sprintf("The website with root uid " . $rootUid . " routing index has been updated"));
        }
    }
}
