package servers

import "sync"

var listenServersLock sync.Mutex
var connectServersLock sync.Mutex
var listenServers []*Server
var connectServers []*Server

//AddWaitAuthServer 添加认证服务器
func AddWaitAuthServer(server *Server, IsListenServer bool) {
	if server.Agent == nil {
		return
	}

	if IsListenServer {
		func(server *Server) {
			listenServersLock.Lock()
			defer listenServersLock.Unlock()
			listenServers = append(listenServers, server)
		}(server)
	} else {
		func(server *Server) {
			connectServersLock.Lock()
			defer connectServersLock.Unlock()
			connectServers = append(connectServers, server)
		}(server)
	}
}

func removeListenServer(server *Server) {
	listenServersLock.Lock()
	defer listenServersLock.Unlock()
	for k, v := range listenServers {
		if v == server {
			listenServers[k] = listenServers[len(listenServers)-1]
			listenServers = listenServers[:len(listenServers)-1]
			return
		}
	}
}

func removeConnectServer(server *Server) {
	connectServersLock.Lock()
	defer connectServersLock.Unlock()
	for k, v := range connectServers {
		if v == server {
			connectServers[k] = connectServers[len(connectServers)-1]
			connectServers = connectServers[:len(connectServers)-1]
			return
		}
	}
}

//RemoveAuthServer 删除服务器
func RemoveAuthServer(server *Server) {
	removeListenServer(server)
	removeConnectServer(server)
}

//RangeListenServer 遍历服务器
func RangeListenServer(f func(*Server)) {
	listenServersLock.Lock()
	defer listenServersLock.Unlock()
	for _, v := range listenServers {
		f(v)
	}
}

func MoveToServers(server *Server) {
	RemoveAuthServer(server)
	AddServer(server)
}
