<?php

namespace App\EntityListener;

use App\Entity\Dashboard;
use App\Service\DashboardService;
use Symfony\Component\DependencyInjection\ContainerInterface;

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

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

    /**
     * @param Dashboard $dashboard
     */
    public function postUpdate(Dashboard $dashboard)
    {
        if (!$dashboard->isMain()) {
            return;
        }
        $dashboardService = $this->container->get(DashboardService::class);
        $dashboards = $dashboardService->getOtherDashboardsForUser($dashboard);

        foreach ($dashboards as $otherDashboard) {
            $otherDashboard->setMain(false);
            $dashboardService->save($otherDashboard);
        }
    }
}
