package loadmodule

import (
	"errors"
	"math/rand"
	"net/url"
	"strings"
)

//负载-随机

type RandomProxy struct {
	curIndex int
	rss      []*url.URL
}

func (r *RandomProxy) Add(param string) error {
	urlParam := param
	if params := strings.Split(param, "|"); len(params) == 2 {
		urlParam = params[0]
	}
	if len(param) == 0 {
		return errors.New("param len 1 at least")
	}
	remoteUrl, err := url.Parse(strings.TrimSpace(urlParam))
	if err != nil {
		return err
	}
	r.rss = append(r.rss, remoteUrl)
	return nil
}

func (r *RandomProxy) Next() *url.URL {
	if len(r.rss) == 1 {
		return r.rss[0]
	}
	r.curIndex = rand.Intn(len(r.rss))
	return r.rss[r.curIndex]
}

func (r *RandomProxy) Get() *url.URL {
	return r.Next()
}

func (r *RandomProxy) Len() int {
	return len(r.rss)
}

func (r *RandomProxy) Update() {

}
