package types

import (
	"github.com/juju/errors"
	"github.com/pingcap/schrodinger/config"
)

// Endpoint is endpoint that identify idc 、pod、 host, etc
// Buildin endpoints
// idc:
//    should have label key "idc"
type Endpoint struct {
	// ID is endpoint id
	ID int64 `json:"id"`
	*Meta
	// Type is which type the endpoint is, like idc、pod、host
	Type string `json:"type"`
	// Name names the endpoint
	Name string `json:"name"`
	// Value is the value of endpoint
	Value string `json:"value"`
	Ctime string `json:"create_time"`
	Utime string `json:"update_time"`
}

// Verify verifies endpoint
func (r *Endpoint) Verify() error {
	if r.Name == "" {
		return errors.BadRequestf("endpoint name can't be empty")
	}
	if r.Type == "" {
		return errors.BadRequestf("endpoint type can't be empty")
	}
	return r.verifyIfBuildIn()
}

func (r *Endpoint) verifyIfBuildIn() error {
	switch r.Type {
	case "idc":
		if _, ok := r.Labels[config.GetGlobalConfig().Label.IdcKey]; !ok {
			return errors.Errorf("endpoint %v does not have key %s", r, config.GetGlobalConfig().Label.IdcKey)
		}
	default:
		return nil
	}
	return nil
}

// Clone clones endpoint
func (r *Endpoint) Clone() *Endpoint {
	objectCopy := &Endpoint{
		ID:    r.ID,
		Name:  r.Name,
		Type:  r.Type,
		Value: r.Value,
		Meta:  r.Meta,
		Ctime: r.Ctime,
		Utime: r.Utime,
	}
	return objectCopy
}
