package transport

import (
	
	
	

	
	

	
	
)

type obfListener struct {
	listener net.Listener
}

type obfConn struct {
	reader io.Reader
	writer io.Writer
	net.Conn
}

func ( *obfConn) ( []byte) (int, error) {
	return .reader.Read()
}

func ( *obfConn) ( []byte) (int, error) {
	return .writer.Write()
}

// ObfuscatedListener creates new obfuscated2 listener using given net.Listener.
//
// Useful for creating Telegram servers:
//
//	transport.Listen(transport.ObfuscatedListener(ln))
func ( net.Listener) net.Listener {
	return obfListener{listener: }
}

// Accept waits for and returns the next connection to the listener.
func ( obfListener) () ( net.Conn,  error) {
	,  := .listener.Accept()
	if  != nil {
		return nil, 
	}
	defer func() {
		if  != nil {
			multierr.AppendInto(&, .Close())
		}
	}()

	, ,  := obfuscated2.Accept(, nil)
	if  != nil {
		return nil, errors.Wrap(, "accept")
	}

	var  *bytes.Reader
	if .Protocol[0] == codec.AbridgedClientStart[0] {
		// Abridged sends only byte for tag.
		 = bytes.NewReader(.Protocol[:1])
	} else {
		 = bytes.NewReader(.Protocol[:])
	}

	 := &obfConn{
		reader: io.MultiReader(, ),
		writer: ,
		Conn:   ,
	}

	return , nil
}

// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
func ( obfListener) () error {
	return .listener.Close()
}

// Addr returns the listener's network address.
func ( obfListener) () net.Addr {
	return .listener.Addr()
}