package client

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

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

func NewReferer(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
	}
	ref.urlobj = urlobj
	if !strings.Contains(ref.urlobj.Host, ":") {
		portstr := strconv.FormatInt(int64(DefaultServicePort), 10)
		ref.urlobj.Host = ref.urlobj.Host + ":" + portstr
	}
	return ref, err
}

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

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
	}
}
