package ip

import (
	"net"
)

type Cache struct {
	resolver NetInterfaceIPResolver
	items    map[string]net.IP
}

func NewCache(resolver NetInterfaceIPResolver) *Cache {
	return &Cache{
		resolver: resolver,
		items:    make(map[string]net.IP),
	}
}

func (c Cache) Get(name string) (net.IP, error) {
	// Return cached entry.
	if cached, ok := c.items[name]; ok {
		return cached, nil
	}

	ip, err := c.resolver(name)
	if err == nil {
		c.Set(name, ip)
	}
	return ip, err
}

func (c *Cache) Set(name string, ip net.IP) {
	c.items[name] = ip
}
