package main

import (
	"net"
	"./log"
	"sync"
	"time"
)

type proxyInfo struct {
	sync.RWMutex
	infoIps []string
	index   int
}

func newProxyInfo(addrS []string) *proxyInfo {
	p := &proxyInfo{
		infoIps: []string{},
	}
	p.ResetAddr(addrS)
	return p
}

func (pi *proxyInfo) getOneProxyAddr() (string, bool) {
	pi.Lock()
	defer pi.Unlock()
	lenIps := len(pi.infoIps)
	if lenIps == 0 {
		log.Error("There is no addr can be connected")
		return "", false
	}
	pi.index++
	if pi.index >= lenIps {
		pi.index = 0
	}
	ip := pi.infoIps[pi.index]
	return ip, true
}

func (pi *proxyInfo) ResetAddr(addrS []string) bool {
	if addrS == nil || len(addrS) == 0 {
		return false
	}
	pi.Lock()
	defer pi.Unlock()
	pi.infoIps = addrS
	return true
}

func DialTest(addr string) bool {
	conn, err := net.DialTimeout("tcp", addr, time.Second)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}
