package Nrestful

import (
	l4g "proxy/logger" //"github.com/sirupsen/logrus"
	"sync"
)

var mutex sync.Mutex

type Port struct {

	CurIndex int
	UseFlag int
	
	Dst_id uint16
	Rsp chan RestRsp
}

const MAX_PORT_NUM uint16 = 8192

type PortMngt struct {
	Seq uint16
	CurIndex uint16
	Ports [MAX_PORT_NUM]Port 
}

var portMngt PortMngt

func AssignPort(req *RestReq) *Port {
	var id uint16 = 0
	var i uint16 = 0
	var port *Port = nil
	
	mutex.Lock()
	for i=0; i<MAX_PORT_NUM; i++ {
		id = (i+portMngt.CurIndex) % MAX_PORT_NUM
		if portMngt.Ports[id].UseFlag == 0 {
			portMngt.CurIndex = (id + 1) % MAX_PORT_NUM
			portMngt.Ports[id].UseFlag = 1
			req.Src_id = id
			req.Dst_id = portMngt.Seq
			portMngt.Ports[id].Dst_id = req.Dst_id
			portMngt.Seq ++
			
			port = &portMngt.Ports[id]
			break
		}
	}
	mutex.Unlock()
	
	return port
}

func GetPortInfo(src_id uint16, dst_id uint16) *Port {
	if src_id < 0 || src_id >= MAX_PORT_NUM {
		return nil
	}
	
	port := &portMngt.Ports[src_id]
	if port.UseFlag == 0 || port.Dst_id != dst_id {
		l4g.RestLog.Errorf("Get port error, src[%d], dst[%d], used_flag[%d]", src_id, dst_id, port.UseFlag)
		return nil
	}
	
	return port
}

/*func ClosePortChan(id int, ts int64) {
	if id < 0 || id >= MAX_PORT_NUM {
		return 
	}
	
	mutex.Lock()
	if portMngt.Ports[id].UseFlag && (ts == portMngt.Ports[id].Ts) {
		close(portMngt.Ports[id].Rsp)
	}
	mutex.Unlock()
	
	return
}*/

func ReleasePort(id uint16) int {
	if id < 0 || id >= MAX_PORT_NUM {
		return -1
	}
	
	mutex.Lock()
	portMngt.Ports[id].UseFlag = 0
	mutex.Unlock()
	
	return 0
}
