package loadmodule

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

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

func (h *HashProxy) 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))
	}
	h.rss = append(h.rss, remoteUrl)
	return nil
}

func (h *HashProxy) next(ip string) (url *url.URL, err error) {
	defer func() {
		//数组线程不安全处理
		if rec := recover(); rec != nil {
			err = NewErrorWithCode(GATEWAY_MODULE_SERVER_ERR, fmt.Sprintf("服务列表%v 获取服务异常%v ", h.rss, rec))
		}
	}()
	if len(h.rss) == 1 {
		url = h.rss[0]
		return
	}
	url = h.rss[int64(adler32.Checksum([]byte(ip)))]
	return
}

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

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