<?php
declare(strict_types=1);

namespace App\Service\Network;

use App\Entity\Network\NetworkOrganization;
use App\Entity\Organization\Organization;
use App\Enum\Network\NetworkEnum;
use App\Service\Utils\DatesUtils;
use App\Tests\Service\Network\UtilsTest;

/**
 * Class Utils : service rassemblant des fonctions d'aides pour les questions se rapportant au réseau
 * @package App\Service\Network
 */
class Utils
{
    /**
     * Test si l'organisation appartient au réseau de la CMF
     * @param Organization $organization
     * @return bool
     * @see UtilsTest::testIsCmf()
     */
    public function isCMF(Organization $organization): bool
    {
        return $this->doesOrganizationBelongToTheNetwork($organization, NetworkEnum::CMF());
    }

    /**
     * Test si l'organisation appartient au réseau de la CMF Actuellement
     * @param Organization $organization
     * @return bool
     * @see UtilsTest::testIsCmfAndActiveNow()
     */
    public function isCMFAndActiveNow(Organization $organization): bool
    {
        return $this->doesOrganizationBelongToTheNetwork($organization, NetworkEnum::CMF(), true);
    }

    /**
     * Teste si l'organisation appartient à un réseau
     *
     * @param Organization $organization
     * @param NetworkEnum $network  id du réseau
     * @param bool $activeNow  si true, on teste en plus l'activité aujourd'hui
     * @return boolean
     * @see UtilsTest::testIsOrganizationBelongToTheNetwork()
     */
    public function doesOrganizationBelongToTheNetwork(Organization $organization, NetworkEnum $network, ?bool $activeNow = false): bool
    {
        $networksOrganizations = $organization->getNetworkOrganizations();
        /** @var NetworkOrganization $networksOrganization */
        foreach ($networksOrganizations as $networksOrganization) {
            if ($networksOrganization->getNetwork()->getId() === $network->getValue()) {
                return !$activeNow || $this->isNetworkOrganizationActiveNow($networksOrganization);
            }
        }
        return false;
    }


    /**
     * @param NetworkOrganization $networksOrganization
     * @return bool
     * @throws \Exception
     */
    public function isNetworkOrganizationActiveNow(NetworkOrganization $networksOrganization): bool
    {
        return $networksOrganization->getStartDate() && DatesUtils::isIntervalIsValidNow($networksOrganization->getStartDate(), $networksOrganization->getEndDate());
    }
}
