<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Command;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cli\CommandController;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Flow\ResourceManagement\ResourceRepository;
use Newland\Toubiz\Sync\Neos\Domain\Model\Medium;
use Newland\Toubiz\Sync\Neos\Domain\Repository\MediumRepository;
use Symfony\Component\Console\Helper\ProgressBar;

class MediaCommandController extends CommandController
{

    /**
     * @var MediumRepository
     * @Flow\Inject()
     */
    protected $mediaRepository;

    /**
     * @var ResourceRepository
     * @Flow\Inject()
     */
    protected $resourceRepository;

    /**
     * @var PersistenceManagerInterface
     * @Flow\Inject()
     */
    protected $persistenceManager;

    /** @var int */
    protected $persistEvery = 100;

    /**
     * Deletes downloaded version of media objects form the database.
     * This does not delete the media objects themselves, but only the local files for them.
     * Images will continue to be shown as before, but after deleting local images they will be
     * loaded from a remote location instead of the webserver itself.
     */
    public function deleteLocalImagesCommand(): void
    {
        $progress = new ProgressBar($this->output->getOutput());
        $progress->start($this->mediaRepository->countAllWithLocalResource());

        $i = 0;
        foreach ($this->mediaRepository->findAllWithLocalResource() as $medium) {
            /** @var Medium $medium */
            $this->resourceRepository->remove($medium->getResource());
            $medium->setResource(null);
            $this->mediaRepository->update($medium);
            $progress->advance();

            if (++$i % $this->persistEvery === 0) {
                $this->persistenceManager->persistAll();
            }
        }

        $progress->finish();
        $this->outputLine();
    }
}
