<?php

class Hub_model extends Cf_Model
{
    public function getHubInfo($restClient = null)
    {
        $restClient = $restClient instanceof HttpClientInterface ? $restClient : $this->getRestClient();
        $result = [
            'version' => CFE_MAJOR_MINOR_VERSION,
            'release' => ['version' => CFE_RELEASE_VERSION, 'isAlpha' => str_ends_with(CFE_RELEASE_VERSION, 'a')],
        ];
        $apiInfo = json_decode($restClient->get('/'), JSON_OBJECT_AS_ARRAY);
        if (isset($apiInfo['data'][0]['hub']) && is_array($apiInfo['data'][0]['hub'])) {
            $result = array_merge($result, $apiInfo['data'][0]['hub']);
        }

        // get IPv4 addresses from the inventory, api status call returns only 1 IP addr, even if multiple were reported
        if (isset($result['hostkey'])) {
            $this->load->model('host_model');
            $ip = $this->host_model->getHostVariableDataByName($result['hostkey'], "IPv4 addresses");
            $result['ip'] = $ip ?? $result['ip'];
        }

        $result['fr'] = json_decode($restClient->get('/fr/hub-status'), JSON_OBJECT_AS_ARRAY);
        return $result;
    }

    public function getHostkey()
    {
        $this->load->model('api_rest_model');
        $info = $this->api_rest_model->get_api_details();
        return $info['hub']['hostkey'] ?? null;
    }
}
