package node

import (
	"regexp"

	"code.fbi.h-da.de/danet/gosdn/models/generated/openconfig"
)

// Node is a representation of a network element.
type Node struct {
	ID       string
	Name     string
	Kind     string
	Image    string
	MgmtIpv4 string
	YangData openconfig.Device
}

// GetID gets the id.
func (n Node) GetID() string {
	return n.ID
}

// FillAllFields fills all remaining fields of object with data from YangData.
func (n *Node) FillAllFields(containerRegistryURL string) {
	// Works if linux and our gnmi target is used.
	softwareVersion := n.YangData.System.State.SoftwareVersion
	if softwareVersion != nil {
		// Checks if software version is in compatible format.
		result, _ := regexp.MatchString(`^([A-Za-z0-9\.\/])*:([A-Za-z0-9\.])*`, *softwareVersion)
		if result {
			n.Kind = "linux"
			n.Image = containerRegistryURL + *softwareVersion
			return
		}

		n.Kind = "couldn't detect kind"
		n.Image = "couldn't detect image"
		return
	}

	// Specific to arista
	regex := regexp.MustCompile(`[0-9]+\.[0-9]+\.[0-9][A-Z]`)
	dockerTag := string(regex.FindAll([]byte(*n.YangData.Lldp.Config.SystemDescription), 1)[0])

	// If it's not linux with our gnmi target and not arista, we don't support it.
	if len(dockerTag) == 0 {
		n.Kind = "couldn't detect kind"
		n.Image = "couldn't detect image"
		return
	}

	n.Kind = "ceos"
	n.Image = containerRegistryURL + n.Kind + ":" + dockerTag
}
