package loadmodule

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

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

func (r *RoundRobinProxy) 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 *RoundRobinProxy) 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))
		}
	}()

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

func (r *RoundRobinProxy) 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 *RoundRobinProxy) 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
}
