package main

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"os"
	"strconv"
	"strings"
	"time"

	"../../RequestCenter"
)

func main() {
	var srcHost, agencyHost string
	flag.StringVar(&srcHost, "srcHost", "", "srcHost")
	flag.StringVar(&agencyHost, "agencyHost", "", "agencyHost")
	flag.Parse()
	if srcHost == "" || agencyHost == "" {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", "参数为空")
		os.Exit(1)
	}
	Log("已成功将" + srcHost + "代理到" + agencyHost)
	//建立socket,监听端口
	netListen, err := net.Listen("tcp", srcHost)
	CheckError(err)
	Log("Waiting for clients")

	defer netListen.Close()
	for {
		conn, err := netListen.Accept()
		//如果没有请求就一直等待
		if err == nil {
			Log(conn.RemoteAddr().String(), " tcp connect success ", conn.LocalAddr())
			chanmsg := make(chan int)
			go handleConnection(conn, agencyHost, chanmsg)
			if <-chanmsg == 1 {
				conn.Close()
				//Log("链接被关闭!")
			}
		}
	}
}

//处理连接
func handleConnection(conn net.Conn, agencyHost string, chanmsg chan int) {
	var baseReq = RequestCenter.CreateRequestWithConn(conn)
	buffer := baseReq.ReceiveData(5000)
	if len(buffer) > 1 {
		arr := strings.Split(string(buffer), "\r\n")
		if len(arr) > 1 {
			arr[1] = "Host: " + agencyHost
			newstr := strings.Join(arr, "\r\n")
			Log(newstr)
			SendAgencyHost([]byte(newstr), baseReq, agencyHost)
		}
	}
	chanmsg <- 1
}
func SendAgencyHost(data []byte, baseconn *RequestCenter.QRequest, agencyHost string) {
	var agencyReq = RequestCenter.CreateRequest("tcp", agencyHost)
	agencyReq.SendData(nil, data)
	var buf bytes.Buffer

	bufferHead := agencyReq.ReceiveData(5000)
	if len(bufferHead) > 0 {
		buf.Write(bufferHead)
	}
	time.Sleep(10 * time.Millisecond)
	bufferBody := agencyReq.ReceiveData(5000)
	if len(bufferBody) > 0 {
		buf.Write(bufferBody)
	}
	Log(strconv.Itoa(buf.Len()))
	Log(string(buf.Bytes()))
	baseconn.SendData(nil, buf.Bytes())
	agencyReq.Close()
}

//打印信息统一方法
func Log(v ...interface{}) {
	log.Println(v...)
}

//执行错误处理方法
func CheckError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}