<?php

namespace App\EntityListener;

use App\Entity\ClientContact;
use App\Service\ClientContactService;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\DependencyInjection\ContainerInterface;

final class ClientContactListener
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param ClientContact $contact
     * @ORM\PostUpdate()
     * @ORM\PostPersist()
     */
    public function updateMain(ClientContact $contact)
    {
        if (!$contact->isMain()) {
            return;
        }
        $clientContactService = $this->container->get(ClientContactService::class);
        $contacts = $clientContactService->getOtherContactsForClient($contact);

        /** @var ClientContact $otherContact */
        foreach ($contacts as $otherContact) {
            $otherContact->setMain(false);
            $clientContactService->save($otherContact);
        }
    }
}
