<?php

namespace Opentalent\OtCore\Domain\Repository;

use DateTimeZone;
use GuzzleHttp\Exception\GuzzleException;
use Opentalent\OtCore\Domain\Model\Member;
use Opentalent\OtCore\Exception\ApiRequestException;

class MemberRepository extends BaseApiRepository
{
    const URI_TRAILING_PART = '/api/public/members';
    const HYDRA_TYPE = 'PortailMemberBySpeciality';

    /**
     * Get the members of the organization
     * If $only_ca is true, returns only the members onf the CA
     *
     * @param int $organizationId The id of the organization
     * @return ApiPagedCollection              Members
     * @throws ApiRequestException
     */
    public function findByOrganizationId(int $organizationId) {
        $params = [];
        $params['filter[where][organizationId]'] = $organizationId;
        $params['itemsPerPage'] = '20000';  // TODO: désactiver la pagination et mieux filtrer quand ce repo sera branché sur la NV,
                                            // certaines écoles ont des centaines de membres, et pour l'instant les rôles ne sont filtrés qu'après la requête...
        return $this->getApiRecords($params);
    }

    /**
     * Returns a Member object from an Api record
     *
     * @param $record
     * @return Member|null
     * @throws \Exception
     */
    protected function memberToObject(array $record): ?Member {
        if ($record['@type'] != $this::HYDRA_TYPE) {
            return null;
        }
        $member = new Member();
        $a = explode('/', $record['@id']);
        $member->setId(end($a));
        $member->setOrganizationId((int)$record['organizationId']);
        $member->setGender($record['gender']);
        $member->setGivenName($record['givenName']);
        $member->setName($record['name']);
        $dateStart = new \DateTime($record['startDate']);
        $dateStart->setTimezone(new \DateTimeZone('Europe/Paris'));
        $member->setStartDate($dateStart);
        if ($record['endDate'] !== null) {
            $dateEnd = new \DateTime($record['endDate']);
            $dateEnd->setTimezone(new \DateTimeZone('Europe/Paris'));
            $member->setEndDate($dateEnd);
        }
        if (isset($record['instrumentGroup'])) {
            $member->setInstrumentGroup($record['instrumentGroup']);
        }
        if (isset($record['instrument'])) {
            $member->setInstrument($record['instrument']);
        }
        if (isset($record['mission'])) {
            $member->setMission($record['mission']);
        }
        $member->setPersonId((int)$record['personId']);
        $member->setImage($record['image']);

        return $member;
    }
}
