package pgproto3

import (
	
	
	
	
)

// Backend acts as a server for the PostgreSQL wire protocol version 3.
type Backend struct {
	cr *chunkReader
	w  io.Writer

	// tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced
	// before it is actually transmitted (i.e. before Flush).
	tracer *tracer

	wbuf []byte

	// Frontend message flyweights
	bind           Bind
	cancelRequest  CancelRequest
	_close         Close
	copyFail       CopyFail
	copyData       CopyData
	copyDone       CopyDone
	describe       Describe
	execute        Execute
	flush          Flush
	functionCall   FunctionCall
	gssEncRequest  GSSEncRequest
	parse          Parse
	query          Query
	sslRequest     SSLRequest
	startupMessage StartupMessage
	sync           Sync
	terminate      Terminate

	bodyLen    int
	msgType    byte
	partialMsg bool
	authType   uint32
}

const (
	minStartupPacketLen = 4     // minStartupPacketLen is a single 32-bit int version or code.
	maxStartupPacketLen = 10000 // maxStartupPacketLen is MAX_STARTUP_PACKET_LENGTH from PG source.
)

// NewBackend creates a new Backend.
func ( io.Reader,  io.Writer) *Backend {
	 := newChunkReader(, 0)
	return &Backend{cr: , w: }
}

// Send sends a message to the frontend (i.e. the client). The message is not guaranteed to be written until Flush is
// called.
func ( *Backend) ( BackendMessage) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceMessage('B', int32(len(.wbuf)-), )
	}
}

// Flush writes any pending messages to the frontend (i.e. the client).
func ( *Backend) () error {
	,  := .w.Write(.wbuf)

	const  = 1024
	if len(.wbuf) >  {
		.wbuf = make([]byte, 0, )
	} else {
		.wbuf = .wbuf[:0]
	}

	if  != nil {
		return &writeError{err: , safeToRetry:  == 0}
	}

	return nil
}

// Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function
// PQtrace.
func ( *Backend) ( io.Writer,  TracerOptions) {
	.tracer = &tracer{
		w:             ,
		buf:           &bytes.Buffer{},
		TracerOptions: ,
	}
}

// Untrace stops tracing.
func ( *Backend) () {
	.tracer = nil
}

// ReceiveStartupMessage receives the initial connection message. This method is used of the normal Receive method
// because the initial connection message is "special" and does not include the message type as the first byte. This
// will return either a StartupMessage, SSLRequest, GSSEncRequest, or CancelRequest.
func ( *Backend) () (FrontendMessage, error) {
	,  := .cr.Next(4)
	if  != nil {
		return nil, 
	}
	 := int(binary.BigEndian.Uint32() - 4)

	if  < minStartupPacketLen ||  > maxStartupPacketLen {
		return nil, fmt.Errorf("invalid length of startup packet: %d", )
	}

	,  = .cr.Next()
	if  != nil {
		return nil, translateEOFtoErrUnexpectedEOF()
	}

	 := binary.BigEndian.Uint32()

	switch  {
	case ProtocolVersionNumber:
		 = .startupMessage.Decode()
		if  != nil {
			return nil, 
		}
		return &.startupMessage, nil
	case sslRequestNumber:
		 = .sslRequest.Decode()
		if  != nil {
			return nil, 
		}
		return &.sslRequest, nil
	case cancelRequestCode:
		 = .cancelRequest.Decode()
		if  != nil {
			return nil, 
		}
		return &.cancelRequest, nil
	case gssEncReqNumber:
		 = .gssEncRequest.Decode()
		if  != nil {
			return nil, 
		}
		return &.gssEncRequest, nil
	default:
		return nil, fmt.Errorf("unknown startup message code: %d", )
	}
}

// Receive receives a message from the frontend. The returned message is only valid until the next call to Receive.
func ( *Backend) () (FrontendMessage, error) {
	if !.partialMsg {
		,  := .cr.Next(5)
		if  != nil {
			return nil, translateEOFtoErrUnexpectedEOF()
		}

		.msgType = [0]
		.bodyLen = int(binary.BigEndian.Uint32([1:])) - 4
		.partialMsg = true
	}

	var  FrontendMessage
	switch .msgType {
	case 'B':
		 = &.bind
	case 'C':
		 = &._close
	case 'D':
		 = &.describe
	case 'E':
		 = &.execute
	case 'F':
		 = &.functionCall
	case 'f':
		 = &.copyFail
	case 'd':
		 = &.copyData
	case 'c':
		 = &.copyDone
	case 'H':
		 = &.flush
	case 'P':
		 = &.parse
	case 'p':
		switch .authType {
		case AuthTypeSASL:
			 = &SASLInitialResponse{}
		case AuthTypeSASLContinue:
			 = &SASLResponse{}
		case AuthTypeSASLFinal:
			 = &SASLResponse{}
		case AuthTypeGSS, AuthTypeGSSCont:
			 = &GSSResponse{}
		case AuthTypeCleartextPassword, AuthTypeMD5Password:
			fallthrough
		default:
			// to maintain backwards compatibility
			 = &PasswordMessage{}
		}
	case 'Q':
		 = &.query
	case 'S':
		 = &.sync
	case 'X':
		 = &.terminate
	default:
		return nil, fmt.Errorf("unknown message type: %c", .msgType)
	}

	,  := .cr.Next(.bodyLen)
	if  != nil {
		return nil, translateEOFtoErrUnexpectedEOF()
	}

	.partialMsg = false

	 = .Decode()
	if  != nil {
		return nil, 
	}

	if .tracer != nil {
		.tracer.traceMessage('F', int32(5+len()), )
	}

	return , nil
}

// SetAuthType sets the authentication type in the backend.
// Since multiple message types can start with 'p', SetAuthType allows
// contextual identification of FrontendMessages. For example, in the
// PG message flow documentation for PasswordMessage:
//
//			Byte1('p')
//
//	     Identifies the message as a password response. Note that this is also used for
//			GSSAPI, SSPI and SASL response messages. The exact message type can be deduced from
//			the context.
//
// Since the Frontend does not know about the state of a backend, it is important
// to call SetAuthType() after an authentication request is received by the Frontend.
func ( *Backend) ( uint32) error {
	switch  {
	case AuthTypeOk,
		AuthTypeCleartextPassword,
		AuthTypeMD5Password,
		AuthTypeSCMCreds,
		AuthTypeGSS,
		AuthTypeGSSCont,
		AuthTypeSSPI,
		AuthTypeSASL,
		AuthTypeSASLContinue,
		AuthTypeSASLFinal:
		.authType = 
	default:
		return fmt.Errorf("authType not recognized: %d", )
	}

	return nil
}