<?php

namespace Opentalent\OtCore\Domain\Repository;

use GuzzleHttp\Exception\GuzzleException;
use Opentalent\OtCore\Domain\Model\FederationStructure;
use Opentalent\OtCore\Domain\Model\Organization;
use Opentalent\OtCore\Exception\ApiRequestException;

/**
 * Class FederationStructureRepository
 * @package Opentalent\OtCore\Domain\Repository
 *
 */
class FederationStructureRepository extends BaseApiRepository
{
    const URI_TRAILING_PART = '/api/public/federation_structures';
    const HYDRA_TYPE = 'PortailFederationStructure';

    /**
     * Get the organization's child structures by id
     *
     * @param int $id The id of the organization
     * @param array $searchParams An array of parameters which will be passed to the Api request as URI parameters
     * @param int $page
     * @return ApiPagedCollection
     * @throws ApiRequestException
     */
    public function findChildrenById(int $id, $searchParams = [], $page = 1, $depth = 5): ApiPagedCollection
    {
        $params = [];
        $params['parent'] = $id;
        $params['page'] = $page;
        $params['depth'] = $depth;

        $params = array_merge($params, $searchParams);

        return $this->getApiRecords($params);
    }

    /**
     * Returns an Organization object from an Api record
     *
     * @param array $record
     * @return FederationStructure|null
     */
    protected function memberToObject(array $record): ?FederationStructure {
        if ($record['@type'] != $this::HYDRA_TYPE) {
            return null;
        }

        $federationStructure = new FederationStructure();
        $a = explode('/', $record['@id']);
        $federationStructure->setId(end($a));
        $federationStructure->setName($record['name']);
        $federationStructure->setPrincipalType($record['principalType']);
        $federationStructure->setWebsite($record['website']);
        $federationStructure->setAddressCity($record['addressCity']);
        $federationStructure->setPostalCode($record['postalCode']);
        $federationStructure->setStreetAddress($record['streetAddress']);
        $federationStructure->setLatitude($record['latitude']);
        $federationStructure->setLongitude($record['longitude']);
        $federationStructure->setCountry($record['country']);
        $federationStructure->setCategories($record['categories']);
        if ($record['logoId']) {
            $federationStructure->setLogoUri($this->apiService->getApiUri('_internal/secure/files/') . $record['logoId']);
        }
        $federationStructure->setParentId($record['n1Id']);
        $federationStructure->setParentName($record['n1Name']);
        $federationStructure->setParents($record['parents']);
        return $federationStructure;
    }

}
