<?php
declare(strict_types=1);

namespace App\Service\Network;


use App\Entity\Organization\Organization;
use App\Enum\Organization\PrincipalTypeEnum;
use App\Repository\Network\NetworkOrganizationRepository;
use App\Tests\Service\Network\TreeTest;

/**
 * Class Tree : service rassemblant des fonction pour répondre aux poblématique d'arbre du réseau
 * @package App\Service\Network
 */
class Tree
{
    public function __construct(private NetworkOrganizationRepository $networkOrganizationRepository)
    { }

    /**
     * Retrouve tous les parents d'une structure et les tries selon leur type principal
     * @param Organization $organization
     * @return list<Organization>
     */
    public function findAllParentsAndSortByType(Organization $organization): array
    {
        return $this->sortByType($this->networkOrganizationRepository->findAllParents($organization));
    }

    /**
     * Trie les organisations par rapport à leur type principal :
     * DELEGATION, GROUPMENT, LOCAL_FEDERATION, DEPARTEMENTAL_FEDERATION, REGIONAL_FEDERATION, NATIONAL_FEDERATION
     * @param list<Organization> $organizations
     * @return list<Organization>
     * @see TreeTest::testSortByType()
     */
    public function sortByType(array $organizations): array
    {
        $typeOrder = [
            PrincipalTypeEnum::DELEGATION(),
            PrincipalTypeEnum::GROUPMENT(),
            PrincipalTypeEnum::LOCAL_FEDERATION(),
            PrincipalTypeEnum::DEPARTEMENTAL_FEDERATION(),
            PrincipalTypeEnum::REGIONAL_FEDERATION(),
            PrincipalTypeEnum::NATIONAL_FEDERATION()
        ];

        usort($organizations, static function(Organization $organization1, Organization $organization2) use($typeOrder) {
            return array_keys($typeOrder, $organization1->getPrincipalType()) <=> array_keys($typeOrder, $organization2->getPrincipalType());
        });

        return $organizations;
    }
}
