package loadmodule

import (
	. "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
	"fmt"
	"math/rand"
	"net/url"
	"strings"
	"time"
)

//RandomProxy 负载-随机
type RandomProxy struct {
	rss []*url.URL
}

func (r *RandomProxy) Get(ip string) (url *url.URL, err error) {
	for i := 0; i < 3; i++ {
		url, err = r.next()
		if err == nil {
			return
		}
		time.Sleep(time.Millisecond * 500 * time.Duration(i))
	}
	return
}

func (r *RandomProxy) next() (url *url.URL, err error) {
	defer func() {
		//数组线程不安全处理
		if rec := recover(); rec != nil {
			err = NewErrorWithCode(GATEWAY_MODULE_SERVER_ERR, fmt.Sprintf("服务列表%v 获取服务异常%v ", r.rss, rec))
		}
	}()

	if len(r.rss) == 1 {
		url = r.rss[0]
		return
	}
	return r.rss[rand.Intn(len(r.rss))], nil
}

func (r *RandomProxy) Add(path string) error {
	remoteUrl, err := url.Parse(strings.TrimSpace(path))
	if err != nil {
		return NewErrorWithCode(GATEWAY_MODULE_SERVER_ERR, fmt.Sprintf("服务地址%s ERR:%v", path, err))
	}
	r.rss = append(r.rss, remoteUrl)
	return nil
}

func (r *RandomProxy) Del(path string) error {
	var newRss []*url.URL
	for _, rss := range r.rss {
		if rss.String() == path {
			continue
		}
		newRss = append(newRss, rss)
	}
	r.rss = newRss
	return nil
}
