package SunnyProxy

import (
	"net"
	"sync"
)

type Dns struct {
	SslCertHost string
	records     map[string]string
	Lock        sync.Mutex
}

var DefaultDns = Dns{
	SslCertHost: "sunny.io",
	records:     make(map[string]string),
}

func (dns *Dns) Add(records map[string]string) {
	dns.Lock.Lock()
	for host, remote := range records {
		dns.records[host] = remote
	}
	dns.Lock.Unlock()
}

func (dns *Dns) CustomDialer(addr string) (string, error) {

	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		return addr, err
	}
	dns.Lock.Lock()
	defer dns.Lock.Unlock()
	if destHost, ok := dns.records[host]; ok {
		return destHost + ":" + port, nil
	}
	return addr, nil
}
