<?php

namespace Opentalent\OtTemplating\Domain\Repository;

use Opentalent\OtTemplating\Domain\Model\Donor;
use Opentalent\OtTemplating\Exception\ApiRequestException;

class DonorRepository extends BaseApiRepository
{
    CONST URI = BaseApiRepository::BASE_URI . 'public/donors';
    const HYDRA_TYPE = 'PortailDonor';

    /**
     * Returns a Donor object from an Api record
     *
     * @param $record
     * @return Donor|null
     */
    private function donorFromJson($record) {
        if ($record->{'@type'} != $this::HYDRA_TYPE) {
            return null;
        }
        $donor = new Donor();
        $a = explode('/', $record->{'@id'});
        $donor->setId(end($a));
        $donor->setOrganizationId($record->{'organizationId'});
        $donor->setName($record->{'name'});
        $donor->setEmail($record->{'email'});
        $donor->setTelphone($record->{'telphone'});
        $donor->setWebsite($record->{'website'});
        $donor->setWording($record->{'wording'});
        $donor->setDisplayedOn($record->{'displayedOn'});
        $donor->setLogo($record->{'logo'});

        return $donor;
    }

    /**
     * Returns an array of Donor objects from an array of Api records
     *
     * @param $records
     * @return array
     */
    private function donorsFromJson($records) {
        $donors = [];
        foreach ($records as $record) {
            $donors[] = $this->donorFromJson($record);
        }
        return $donors;
    }

    /**
     * Get the donors of the organization
     *
     * @param int $organizationId The id of the organization
     * @return array              Donors
     * @throws ApiRequestException
     */
    public function findByOrganizationId(int $organizationId) {
        $params = [];
        $params['organizationId'] = $organizationId;

        $records = $this->getApiRecords($this::URI, $params);
        return $this->donorsFromJson($records);
    }

    /**
     * Get the donors of the organization's parents
     *
     * @param int $organizationId The id of the organization
     * @return array              Donors
     * @throws ApiRequestException
     */
    public function findParentsByOrganizationId(int $organizationId) {
        $params = [];
        $params['organizationId'] = $organizationId;
        $params['parent'] = 1;

        $records = $this->getApiRecords($this::URI, $params);
        return $this->donorsFromJson($records);
    }

}
