package types

import (
	"github.com/juju/errors"
)

// Labels alias map[string]string
type Labels map[string]string

// Meta is to provide base data and method for Objects.
// All types of resource that want to use label can inherit Meta struct
// Meta struct implements label interface
type Meta struct {
	// Labels is labels, objects and have meta as it meta messages
	Labels Labels `json:"labels"`
}

// Match match labels, It used for selector to select labels
func (m *Meta) Match(labels map[string]string) bool {
	for key, value := range labels {
		val, ok := m.Labels[key]
		if !ok || val != value {
			return false
		}
	}
	return true
}

// Add adds label to meta's label map
func (m *Meta) Add(key, value string) error {
	if key == "" {
		return errors.New("label key is empty")
	}
	m.Labels[key] = value
	return nil
}

// Has checks is meta has label
func (m *Meta) Has(key string) bool {
	return len(m.Labels[key]) > 0
}

// Get gets key
func (m *Meta) Get(key string) (string, error) {
	val, ok := m.Labels[key]
	if !ok {
		return "", errors.NotFoundf("key %s", key)
	}
	return val, nil
}
