<?php
namespace Newland\Toubiz\Sync\Neos\Command;

use Doctrine\Common\Persistence\ObjectManager;
use Newland\Toubiz\Sync\Neos\Domain\Repository\AddressRepository;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;
use Newland\Toubiz\Sync\Neos\Domain\Repository\CategoryRepository;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Repository\MediumRepository;
use Newland\Toubiz\Sync\Neos\Domain\Repository\SlopeRepository;
use Newland\Toubiz\Sync\Neos\Domain\Repository\TransportationFacilityRepository;

/**
 * @Flow\Scope("singleton")
 */
class OrphansCommandController extends AbstractCommandController
{

    /**
     * @var ObjectManager
     * @Flow\Inject()
     */
    protected $entityManager;

    /**
     * @param bool $quiet
     */
    public function removeCommand($quiet = false)
    {
        /** @var OrphanFinder[] $repositories */
        $repositories = [
            'articles' => $this->objectManager->get(ArticleRepository::class),
            'categories' => $this->objectManager->get(CategoryRepository::class),
            'media elements' => $this->objectManager->get(MediumRepository::class),
            'addresses' => $this->objectManager->get(AddressRepository::class),
            'slopes' => $this->objectManager->get(SlopeRepository::class),
            'transportation facilities' => $this->objectManager->get(TransportationFacilityRepository::class),
        ];

        foreach ($repositories as $name => $repository) {
            $orphans = $this->removeOrphans($repository);
            if (!$quiet) {
                $this->outputLine('Deleted ' . \count($orphans) . ' orphaned ' . $name);
            }
        }
    }

    private function removeOrphans(OrphanFinder $repository): array
    {
        if (method_exists($repository, 'setLanguage')) {
            $repository->setLanguage(null);
        }

        $orphans = $repository->findOrphans();
        foreach ($orphans as $orphan) {
            $repository->remove($orphan);
        }
        $this->entityManager->flush();
        return (array) $orphans;
    }
}
