<?php

namespace AutoAdmin\Bundle\Content\Command;

use AutoAdmin\Bundle\Content\Command\Interfaces\WebsiteCommandInterface;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;


abstract class BaseWebsitesCommand extends Command implements WebsiteCommandInterface
{
    const DEFAULT_LOCALE = 'fr';

    private EntityManagerInterface $manager;
    private SiteContextHelper $siteContextHelper;

    /**
     * @required
     */
    public function initializeCommand(EntityManagerInterface $manager, SiteContextHelper $siteContextHelper): self
    {
        $this->manager = $manager;
        $this->siteContextHelper = $siteContextHelper;

        return $this;
    }

    final public function execute(InputInterface $input, OutputInterface $output): int
    {
        $locale = $this->manager->getRepository(Locale::class)->findOneBy(['code' => self::DEFAULT_LOCALE]);

        try {
            $siteRepo = $this->manager->getRepository(Site::class);
            foreach ($siteRepo->findBy(['enabled' => true]) as $site) {
                $this->siteContextHelper->loadSiteAndLocale($site, $locale);
                $this->do($input, $output);
            }
        } catch (Exception $exception) {
            $output->writeln(sprintf('<error>%s</error>', $exception->getMessage()));
            return Command::FAILURE;
        }


        return Command::SUCCESS;
    }
}
