<?php

namespace api\v2\objects;
use api\v2\Base;

use function api\v2\import_common;
import_common();

/**
 * API wrapper for get_xml_hostgroup_member_objects, look into the function to learn more about the structure of the output
 */
class hostgroupmembers extends Base {
    public function authorized_for_get() {
        return true;
    }

    public function get() {
        global $request;
        $response = get_xml_hostgroup_member_objects($request);
        if(!$response || $response->recordcount == 0) {
            $response = array( "recordcount" => 0, "hostgroup" => [] );
        }
        
        // Ensure object is always an array
        $response = json_decode(json_encode($response), false);
        if (!is_array($response->hostgroup)) {
            $response->hostgroup = [$response->hostgroup];
        }
        foreach($response->hostgroup as $hostgroup) {
            if (!is_array($hostgroup->members->host)) {
                $hostgroup->members->host = [$hostgroup->members->host];
            }
            foreach ($hostgroup->members->host as $host) {
                if (isset($host->host_name)) {
                    $host->name = $host->host_name;
                    unset($host->host_name);
                }
            }
        }
        return $response;
    }
}