<?php
declare(strict_types=1);

namespace App\Service\Export;

use App\ApiResources\Export\ExportRequest;
use App\ApiResources\Export\LicenceCmf\LicenceCmfOrganizationER;
use App\Enum\Core\FileTypeEnum;
use App\Service\Export\Model\LicenceCmf;
use App\Enum\Access\FunctionEnum;
use App\Repository\Organization\OrganizationRepository;
use App\Service\Export\Model\LicenceCmfCollection;

/**
 * Exporte la licence CMF de la structure ou du ou des access, au format demandé
 */
class LicenceCmfExporter extends BaseExporter implements ExporterInterface
{
    public const CMF_ID = 12097;

    /**
     * La couleur de la carte de licence change chaque année, de manière cyclique
     */
    public const LICENCE_CMF_COLOR_START_YEAR = 2020;
    public const LICENCE_CMF_COLOR = [0 => '931572', 1 => 'C2981A', 2 =>  '003882', 3 =>  '27AAE1', 4 =>  '2BB673'];

    public function __construct(
        private OrganizationRepository $organizationRepository
    )
    {}

    public function support($exportRequest): bool
    {
        return $exportRequest instanceof LicenceCmfOrganizationER;
    }

    /**
     * @param LicenceCmfOrganizationER $exportRequest
     * @return LicenceCmfCollection
     */
    public function buildModel(ExportRequest $exportRequest): LicenceCmfCollection
    {
        $organization = $this->accessRepository->find($exportRequest->getRequesterId())?->getOrganization();
        if ($organization === null) {
            throw new \RuntimeException('Unable to determine the organization of the curent user; abort.');
        }

        $licenceCmf = new LicenceCmf();
        $licenceCmf->setId($organization->getId());
        $licenceCmf->setYear($exportRequest->getYear());
        $licenceCmf->setIsOrganizationLicence( $exportRequest instanceof LicenceCmfOrganizationER);
        $licenceCmf->setOrganizationName($organization->getName());
        $licenceCmf->setOrganizationIdentifier($organization->getIdentifier());

        $parentFederation = $organization->getNetworkOrganizations()->get(0)?->getParent();
        if ($parentFederation !== null) {
            $licenceCmf->setFederationName($parentFederation->getName());
        }

        $licenceCmf->setColor(
            $this->getLicenceColor($exportRequest->getYear())
        );

        $logo = $organization->getLogo();
        if ($logo) {
            $licenceCmf->setLogo($logo);
        }

        $presidents = $this->accessRepository->findByOrganizationAndMission($organization, FunctionEnum::PRESIDENT()->getValue());
        if (count($presidents) > 0) {
            $president = $presidents[0]->getPerson();
            if ($president !== null) {
                $licenceCmf->setPersonId($president->getId());
                $licenceCmf->setPersonGender($president->getGender() ?? '');
                $licenceCmf->setPersonFirstName($president->getGivenName());
                $licenceCmf->setPersonLastName($president->getName());
            }
        }

        $cmf = $this->organizationRepository->find(self::CMF_ID);
        /** @noinspection NullPointerExceptionInspection */
        $qrCode = $cmf->getParameters()->getQrCode();
        if ($qrCode) {
            $licenceCmf->setQrCode($qrCode);
        }

        $model = new LicenceCmfCollection();
        $model->setLicences([$licenceCmf]);
        return $model;
    }

    /**
     * @param LicenceCmfOrganizationER $exportRequest
     * @return string
     */
    protected function getFileBasename(ExportRequest $exportRequest): string
    {
        return 'licence_cmf_' . $exportRequest->getYear() . '.pdf';
    }

    /**
     * Retourne le type de fichier tel qu'il apparait au niveau du champ File.type
     *
     * @return FileTypeEnum
     */
    protected function getFileType(): FileTypeEnum
    {
        return FileTypeEnum::LICENCE_CMF();
    }

    /**
     * Retourne la couleur de licence pour l'année donnée
     *
     * @param int $year
     * @return string
     */
    protected function getLicenceColor(int $year): string
    {
        if (!($year > self::LICENCE_CMF_COLOR_START_YEAR)) {
            return self::LICENCE_CMF_COLOR[0];
        }
        return self::LICENCE_CMF_COLOR[($year - self::LICENCE_CMF_COLOR_START_YEAR) % count(self::LICENCE_CMF_COLOR)];
    }
}
