package bootstrap

import (
	"isle/garage"
)

// GaragePeers returns a Peer for each known garage instance in the network.
func (b Bootstrap) GaragePeers() []garage.RemotePeer {

	var peers []garage.RemotePeer

	for _, host := range b.Hosts {

		for _, instance := range host.Garage.Instances {

			peer := garage.RemotePeer{
				ID:        instance.ID,
				IP:        host.IP().String(),
				RPCPort:   instance.RPCPort,
				S3APIPort: instance.S3APIPort,
			}

			peers = append(peers, peer)
		}
	}

	return peers
}

// GarageRPCPeerAddrs returns the full RPC peer address for each known garage
// instance in the network.
func (b Bootstrap) GarageRPCPeerAddrs() []string {
	var addrs []string
	for _, peer := range b.GaragePeers() {
		addr := peer.RPCPeerAddr()
		addrs = append(addrs, addr)
	}
	return addrs
}

// ChooseGaragePeer returns a Peer for a garage instance from the network. It
// will prefer a garage instance on this particular host, if there is one, but
// will otherwise return a random endpoint.
func (b Bootstrap) ChooseGaragePeer() garage.RemotePeer {

	thisHost := b.ThisHost()

	if len(thisHost.Garage.Instances) > 0 {

		inst := thisHost.Garage.Instances[0]
		return garage.RemotePeer{
			ID:        inst.ID,
			IP:        thisHost.IP().String(),
			RPCPort:   inst.RPCPort,
			S3APIPort: inst.S3APIPort,
		}
	}

	for _, peer := range b.GaragePeers() {
		return peer
	}

	panic("no garage instances configured")
}

// GlobalBucketS3APIClient returns an S3 client pre-configured with access to
// the global bucket.
func (b Bootstrap) GlobalBucketS3APIClient() garage.S3APIClient {
	addr := b.ChooseGaragePeer().S3APIAddr()
	creds := b.Garage.GlobalBucketS3APICredentials
	return garage.NewS3APIClient(addr, creds)
}