package tscipher

import (
	"net"
)

type Cipher interface {
	Decrypt(data []byte) (decrypted []byte, err error)
	Encrypt(data []byte) (encryped []byte, err error)
}

type Carrier struct {
	Conn   net.Conn
	Cipher Cipher
	Cache  []byte
}

func NewCipher(cipherName string) (cipher Cipher) {
	if cipherName == "default" {
		return NewChaCha()
	}
	if cipherName == "AES" {
		return NewAES()
	}
	if cipherName == "XOR" {
		return NewXOR([]byte("fasdfasdf"))
	}
	return nil //TODO:临时这样处理
}

func SendData(carrier *Carrier, nByte int) (n int, err error) {
	encrypedByte, err := carrier.Cipher.Encrypt(carrier.Cache[:nByte])
	if err != nil {
		n = 0
		return
	}
	n, err = carrier.Conn.Write(encrypedByte[:nByte])
	return
}

func ReceiveData(carrier *Carrier) (n int, err error) {
	n, err = carrier.Conn.Read(carrier.Cache)
	if err != nil {
		n = 0
		return
	}
	//TODO:err
	decrypted, err := carrier.Cipher.Decrypt(carrier.Cache[:n])
	copy(carrier.Cache, decrypted[:n])

	if err != nil {
		n = 0
		return
	}
	return
}
