package loadmodule

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

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

func (r *RoundRobinProxy) Add(param string) error {
	urlParam := param
	if params := strings.Split(param, "|"); len(params) == 2 {
		urlParam = params[0]
	}
	if len(urlParam) == 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 *RoundRobinProxy) Next() *url.URL {
	if len(r.rss) == 1 {
		return r.rss[0]
	}

	lens := len(r.rss)
	if r.curIndex >= lens {
		r.curIndex = 0
	}
	curAddr := r.rss[r.curIndex]
	r.curIndex = (r.curIndex + 1) % lens
	return curAddr
}

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

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

func (r *RoundRobinProxy) Update() {

}
