package codec

import (
	

	

	
	
)

// PaddedIntermediateClientStart is starting bytes sent by client in Padded intermediate mode.
//
// Note that server does not respond with it.
var PaddedIntermediateClientStart = [4]byte{0xdd, 0xdd, 0xdd, 0xdd}

// PaddedIntermediate is intermediate MTProto transport.
//
// See https://core.telegram.org/mtproto/mtproto-transports#padded-intermediate
type PaddedIntermediate struct{}

var (
	_ TaggedCodec = PaddedIntermediate{}
)

// WriteHeader sends protocol tag.
func ( PaddedIntermediate) ( io.Writer) error {
	if ,  := .Write(PaddedIntermediateClientStart[:]);  != nil {
		return errors.Wrap(, "write padded intermediate header")
	}

	return nil
}

// ReadHeader reads protocol tag.
func ( PaddedIntermediate) ( io.Reader) error {
	var  [4]byte
	if ,  := io.ReadFull(, [:]);  != nil {
		return errors.Wrap(, "read padded intermediate header")
	}

	if  != PaddedIntermediateClientStart {
		return ErrProtocolHeaderMismatch
	}

	return nil
}

// ObfuscatedTag returns protocol tag for obfuscation.
func ( PaddedIntermediate) () [4]byte {
	return PaddedIntermediateClientStart
}

// Write encode to writer message from given buffer.
func ( PaddedIntermediate) ( io.Writer,  *bin.Buffer) error {
	if  := checkOutgoingMessage();  != nil {
		return 
	}

	if  := checkAlign(, 4);  != nil {
		return 
	}

	if  := writePaddedIntermediate(crypto.DefaultRand(), , );  != nil {
		return errors.Wrap(, "write padded intermediate")
	}

	return nil
}

// Read fills buffer with received message.
func ( PaddedIntermediate) ( io.Reader,  *bin.Buffer) error {
	if  := readPaddedIntermediate(, );  != nil {
		return errors.Wrap(, "read padded intermediate")
	}

	return checkProtocolError()
}

func ( io.Reader,  io.Writer,  *bin.Buffer) error {
	 := .Len()

	.Expand(4)
	defer func() {
		.Buf = .Buf[:]
	}()

	,  := io.ReadFull(, .Buf[:+4])
	if  != nil {
		return 
	}
	 := int(.Buf[-1]) % 4
	.Buf = .Buf[:+]

	return writeIntermediate(, )
}

func ( io.Reader,  *bin.Buffer) error {
	if  := readIntermediate(, , true);  != nil {
		return 
	}

	 := .Len() % 4
	.Buf = .Buf[:.Len()-]
	return nil
}