package pubyun

import (
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
	"time"
)

type PubYun struct {
	UserName string
	Password string
}

func New(UserName string, Password string) (*PubYun, error) {
	p := PubYun{
		Password: Password,
		UserName: UserName}
	return &p, nil
}

func (p PubYun) SetDomainRecord(domain, ip string) error {
	url := fmt.Sprintf(
		"http://members.3322.net/dyndns/update?hostname=%s&myip=%s",
		domain,
		ip)

	// Make the HTTP GET request
	req, err := http.NewRequest("GET", url, nil)
	auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", p.UserName, p.Password)))
	req.Header.Set("Authorization", "Basic "+auth)
	if err != nil {
		return err
	}
	time.Sleep(time.Millisecond * 200) // avoid request too fast after login
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	fmt.Println(string(body), resp.Status)
	return nil
}
