package libnmdc

import (
	"net/url"
	"strings"
)

type HubAddress string

func (this *HubAddress) parse() url.URL {
	parsed, err := url.Parse(strings.ToLower(string(*this)))
	if err != nil || len(parsed.Host) == 0 {
		parsed = &url.URL{
			Scheme: "",
			Host:   string(*this),
		}
	}

	// Add default port if not specified
	if !strings.ContainsRune(parsed.Host, ':') {
		parsed.Host = parsed.Host + ":411"
	}

	return *parsed
}

func (this *HubAddress) IsSecure() bool {
	parsed := this.parse()

	return parsed.Scheme == "nmdcs" || parsed.Scheme == "dchubs" || parsed.Scheme == "adcs"
}

func (this *HubAddress) GetHostOnly() string {
	return this.parse().Host
}

func (this *HubAddress) GetProtocol() HubProtocol {
	parsed := this.parse()

	switch parsed.Scheme {
	case "nmdc", "dchub", "nmdcs", "dchubs":
		return HubProtocolNmdc
	case "adc", "adcs":
		return HubProtocolAdc
	default:
		return HubProtocolAutodetect
	}
}
