package registry

import (
	"errors"
	"strconv"
)

var (
	ErrAddressNotExists = errors.New("address not exists")
)

type (
	Addr struct {
		Address string `json:"address"`
		Port    int    `json:"port"`
	}

	ServiceNode struct {
		ID        string            `json:"id"`
		Name      string            `json:"name"`
		Version   string            `json:"version"`
		Status    string            `json:"status"`
		Address   string            `json:"address"`
		Port      int               `json:"port"`
		Addresses map[string]Addr   `json:"addresses"`
		Metadata  map[string]string `json:"metadata"`
	}
)

func (addr Addr) String() string {
	return addr.Address + ":" + strconv.Itoa(addr.Port)
}

func (s *ServiceNode) GetAddress(name string) (addr Addr, err error) {
	if s.Addresses == nil {
		err = ErrAddressNotExists
		return
	}
	var (
		ok bool
	)
	if addr, ok = s.Addresses[name]; !ok {
		err = ErrAddressNotExists
	}
	return
}

func (s *ServiceNode) SetAddress(name string, address string, port int) {
	if s.Addresses == nil {
		s.Addresses = make(map[string]Addr)
	}
	s.Addresses[name] = Addr{
		Address: address,
		Port:    port,
	}
}
