package vmomi

import (
	"context"

	"github.com/vmware/govmomi/view"
	"github.com/vmware/govmomi/vim25"
	"github.com/vmware/govmomi/vim25/mo"
)

func ListVms(client *vim25.Client) ([]*VirtualMachine, error) {
	manager := view.NewManager(client)

	v, err := manager.CreateContainerView(
		context.Background(),
		client.ServiceContent.RootFolder,
		[]string{"VirtualMachine"},
		true,
	)
	if err != nil {
		return nil, err
	}

	var vms []mo.VirtualMachine
	err = v.Retrieve(context.Background(), []string{"VirtualMachine"}, []string{}, &vms)
	if err != nil {
		return nil, err
	}

	var dist []*VirtualMachine
	for i := range vms {
		dist = append(dist, makeVirtualMachine(client, (*MoVirtualMachine)(&vms[i])))
	}

	return dist, nil
}
