package ip

import (
	"errors"
	"net"
)

type CacheDefaultCallback func(name string) (net.IP, error)

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

func NewCache() *Cache {
	return &Cache{
		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
	}
	return nil, errors.New("key did not exist")
}

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

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

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