<?php
include_once __DIR__ . '/BaseLicenseModel.php';
require_once APPPATH . 'modules/advancedreports/services/InventoryAPIService.php';

class License_inventory_model extends Cf_Model implements BaseLicenseModel
{
    /**
     * @var array
     */
    private $variablesMap = [
        'details' => 'CFEngine Enterprise license file',
        'granted' => 'CFEngine Enterprise licenses allocated',
        'utilized' => 'CFEngine Enterprise license utilization',
        'licenseType' => 'CFEngine Enterprise licenses status',
        'owner' => 'CFEngine Enterprise license owner',
        'expires' => 'CFEngine Enterprise license expiration date',
    ];

    /**
     * @return CF_License
     * @throws Exception
     */
    public function getLicenseDetails(): CF_License
    {
        try {
            return new CF_License($this->getDataFromInventory());
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        }
    }

    /**
     * @return array
     * @throws Exception
     */
    private function getDataFromInventory(): array
    {
        $hubID = $this->getHubId();
        $invService = new InventoryAPIService($this->getRestClient());

        $result = json_decode(
            $invService->getData([
                'select' => array_values($this->variablesMap),
                'hostContextInclude' => [str_replace('SHA=', '', $hubID)],
                'limit' => 1,
            ]),
            JSON_OBJECT_AS_ARRAY,
        );

        $licenseData = isset($result['rows'][0]) && sizeof($result['rows'][0]) > 0 ? $result['rows'][0] : null;

        if ($licenseData == null) {
            log_message('debug', "Inventory license data of {$hubID} hub cannot be found");
            return [];
        }

        $mappedResult = [];
        $keys = array_keys($this->variablesMap);
        foreach ($licenseData as $index => $value) {
            $mappedResult[$keys[$index]] = $value;
        }

        return $mappedResult;
    }

    /**
     * @return string|null
     */
    private function getHubId()
    {
        $this->load->model('api_rest_model');
        $info = $this->api_rest_model->get_api_details();
        return isset($info['hub']['hostkey']) ? $info['hub']['hostkey'] : null;
    }
}
