package utils

import (
	"encoding/json"
	"fmt"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/logger/logger"
	"jobarranger2/src/libs/golibs/uds"
	"os"
)

/*
Input hostname (Can add many as you can)
Output hostresult (as much as you requested)
*/
func GetHostInfo(hostData common.HostData) ([]common.HostResult, error) {
	funcName := "GetHostInfo"
	var hostResult []common.HostResult
	// Prepare Event To Get Host IP
	data := common.EventData{
		Event: common.Event{
			Name:      common.EventZabbixHostIp,
			UniqueKey: common.GetUniqueKey(common.ZabbixLinkManagerProcess),
		},
		NextProcess: common.NextProcess{
			Name: common.ZabbixLinkManagerProcess,
			Data: hostData,
		},
	}

	// SocketPath initialization
	socketPath := common.GetCurrentCommunicationSocketPath(data.Event.Name)

	// UDS Client Creation
	udsClient := uds.CreateUdsClient(socketPath, 1)
	udsConn, err := udsClient.Connect()
	if err != nil {
		logger.JaLog("JAUTILS200001", logger.Logging{}, funcName, err.Error())
		os.Exit(1)
	}
	if err := udsConn.Send(data); err != nil {
		return nil, fmt.Errorf("[Error] Uds Send() failed! err: %w", err)
	}

	rawResult, err := udsConn.Receive()
	if err != nil {
		return nil, fmt.Errorf("uds client receive error: %w", err)
	}

	hostResultBytes, err := json.Marshal(rawResult["host_results"])
	if err != nil {
		return nil, fmt.Errorf("marshal Host Result failed: %w", err)
	}

	err = json.Unmarshal(hostResultBytes, &hostResult)
	if err != nil {
		return nil, fmt.Errorf("unmarshal Host Result failed: %w", err)
	}

	return hostResult, nil
}
