package hypervisors

import (
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/sdn/hypervisors"
)

func flattenHypervisorResource(d *schema.ResourceData, hypervisor *hypervisors.RecordHypervisor) {
	d.Set("display_name", hypervisor.DisplayName)
	d.Set("hostname", hypervisor.Hostname)
	d.Set("ip", hypervisor.IP)
	d.Set("name", hypervisor.Name)
	d.Set("ports", flattenPorts(hypervisor.Ports))
	d.Set("status", hypervisor.Status)
	d.Set("created_at", hypervisor.CreatedAt)
	d.Set("synced_at", hypervisor.SyncedAt)
}

func flattenHypervisorListDataSource(hypervisorList hypervisors.HypervisorsList) []map[string]interface{} {
	res := make([]map[string]interface{}, 0, len(hypervisorList))
	for _, v := range hypervisorList {
		temp := map[string]interface{}{
			"display_name": v.DisplayName,
			"hostname":     v.Hostname,
			"ip":           v.IP,
			"name":         v.Name,
			"ports":        flattenPorts(v.Ports),
			"status":       v.Status,
			"created_at":   v.CreatedAt,
			"synced_at":    v.SyncedAt,
		}
		res = append(res, temp)
	}
	return res
}

func flattenHypervisorDataSource(d *schema.ResourceData, hypervisor *hypervisors.RecordHypervisor) {
	d.Set("display_name", hypervisor.DisplayName)
	d.Set("hostname", hypervisor.Hostname)
	d.Set("ip", hypervisor.IP)
	d.Set("name", hypervisor.Name)
	d.Set("ports", flattenPorts(hypervisor.Ports))
	d.Set("status", hypervisor.Status)
	d.Set("created_at", hypervisor.CreatedAt)
	d.Set("synced_at", hypervisor.SyncedAt)
}

func flattenPorts(ports hypervisors.Ports) []map[string]interface{} {
	final := make([]map[string]interface{}, 0)

	res := map[string]interface{}{}

	data := make([]map[string]interface{}, 0)
	info := map[string]interface{}{}

	for _, v := range ports.Data {
		temp := map[string]interface{}{
			"id":                v.ID,
			"unique_identifier": v.UniqueIdentifier,
			"display_name":      v.DisplayName,
			"up":                v.UP,
		}
		data = append(data, temp)
	}

	info["active_ports"] = ports.Info.ActivePorts
	info["total_ports"] = ports.Info.TotalPorts

	res["data"] = data
	res["info"] = []interface{}{info}

	final = append(final, res)

	return final
}
