package accntcli

import (
	"net/url"
	"path"
	"strings"
)

type Referer struct {
	urlobj     *url.URL
	user, pass string
	obj, oper  string
}

func NewReferer(hostname, object, operation string) (*Referer, error) {
	ref := &Referer{
		obj:  object,
		oper: operation,
	}
	if !strings.Contains(hostname, "://") {
		hostname = "https://" + hostname
	}
	urlobj, err := url.Parse(hostname)
	if err != nil {
		return ref, err
	}
	if urlobj.User != nil {
		ref.user = urlobj.User.Username()
		ref.pass, _ = urlobj.User.Password()
		urlobj.User = nil
	}
	urlobj.Path = "/"
	ref.urlobj = urlobj
	return ref, err
}

func ParseHostinfo(hostname string) (*Referer, error) {
	ref := &Referer{}
	if !strings.Contains(hostname, "://") {
		hostname = "https://" + hostname
	}
	urlobj, err := url.Parse(hostname)
	if err != nil {
		return ref, err
	}
	if urlobj.User != nil {
		ref.user = urlobj.User.Username()
		ref.pass, _ = urlobj.User.Password()
		urlobj.User = nil
	}
	urlobj.Path = "/"
	ref.urlobj = urlobj
	return ref, err
}

func (ref *Referer) Host() string {
	return ref.urlobj.Host
}

func (ref *Referer) Raw() string {
	return path.Join(ref.urlobj.Host, "/v3/api/", ref.obj, ref.oper)
}

func (ref *Referer) Point() string {
	curl := ref.urlobj.JoinPath("/v3/api/", ref.obj, ref.oper)
	return curl.String()
}

func (ref *Referer) Userinfo() (string, string) {
	return ref.user, ref.pass
}

func (ref *Referer) SetUserinfo(user, pass string) {
	if user != "" && pass != "" {
		ref.user, ref.pass = user, pass
	}
}
