package main

import (
	"github.com/TransX/tscipher"
	"log"
	"net"
	"os"
	"testing"
	"time"
)

func server(t *testing.T) {
	listener, err := net.Listen("tcp4", "127.0.0.1:1244")
	if err != nil {
		t.Fatal(err)
	}
	for {
		conn, err := listener.Accept()
		log.Println("Test Server Incoming", conn.RemoteAddr().String())
		if err != nil {
			t.Fatal(err)
		}
		bytes := make([]byte, 32)
		XOR := tscipher.NewXOR([]byte("fasdfasdf"))
		n, err := conn.Read(bytes)
		decryped, _ := XOR.Decrypt(bytes[:n])
		copy(bytes, decryped[:n])
		log.Println("Test Server Receive ", string(bytes[:n]))
		encrypted, _ := XOR.Encrypt([]byte("OK"))
		_, err = conn.Write(encrypted)
		log.Println("Test Server write")
		if err != nil {
			t.Fatal(err)
		}
		conn.Close()
		log.Println("Test Server closed")
	}
}

func client(t *testing.T) {
	for {
		conn, err := net.Dial("tcp4", "127.0.0.1:1200")
		if err != nil {
			t.Fatal(err)
		}
		XOR := tscipher.NewXOR([]byte("fasdfasdf"))
		encrypted, _ := XOR.Encrypt([]byte("Client"))
		conn.Write(encrypted)
		log.Println("Test Client write")
		bytes := make([]byte, 32)
		n, err := conn.Read(bytes)
		decryped, _ := XOR.Decrypt(bytes[:n])
		copy(bytes, decryped[:n])
		log.Println("Test Client read")
		if err != nil {
			t.Fatal(err)
		}
		log.Println("Test Client Receive ", string(bytes[:n]))
		time.Sleep(time.Second * 2)
		conn.Close()
		log.Println("Test Client closed")

	}
}

func TestTunnel(t *testing.T) {
	file, _ := os.Create("log.txt")
	log.SetOutput(file)
	//	t.Log("Start testing.")
	log.Println("Test Start testing.")
	go server(t)
	go client(t)
	trans := NewTransTCP()
	trans.Start("1200", "127.0.0.1", "1244")
}
