<?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
     * @param bool $only_ca If true, returns the CA members instead of all the members
     * @return ApiPagedCollection              Members
     * @throws ApiRequestException
     */
    public function findByOrganizationId(int $organizationId) {
        $params = [];
        $params['filter[where][organizationId]'] = $organizationId;
        $params['itemsPerPage'] = '200';
        return $this->getApiRecords($params);
    }

    /**
     * Returns a Member object from an Api record
     *
     * @param $record
     * @return Member|null
     * @throws \Exception
     */
    protected function memberToObject(array $record) {
        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['datetimeStart']);
        $dateStart->setTimezone(new \DateTimeZone('Europe/Paris'));
        $member->setStartDate($dateStart);
        $dateEnd = new \DateTime($record['datetimeStart']);
        $dateEnd->setTimezone(new \DateTimeZone('Europe/Paris'));
        $member->setEndDate($dateEnd);
        $member->setInstrumentGroup($record['instrumentGroup']);
        $member->setInstrument($record['instrument']);
        $member->setMission($record['mission']);
        $member->setPersonId((int)$record['personId']);
        $member->setImage($record['image']);
        $member->setAddressCity($record['addressCity']);
        $member->setStreetAddress($record['streetAddress']);
        $member->setStreetAddressSecond($record['streetAddressSecond']);
        $member->setStreetAddressThird($record['streetAddressThird']);
        $member->setPostalCode($record['postalCode']);
        $member->setTelphone($record['telphone']);
        $member->setMobilPhone($record['mobilPhone']);
        $member->setEmail($record['email']);

        return $member;
    }
}
