package pgproto3

import (
	
	
	
	
	
)

// Frontend acts as a client for the PostgreSQL wire protocol version 3.
type Frontend 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). It is safe to change this variable when the Frontend is
	// idle. Setting and unsetting tracer provides equivalent functionality to PQtrace and PQuntrace in libpq.
	tracer *tracer

	wbuf []byte

	// Backend message flyweights
	authenticationOk                AuthenticationOk
	authenticationCleartextPassword AuthenticationCleartextPassword
	authenticationMD5Password       AuthenticationMD5Password
	authenticationGSS               AuthenticationGSS
	authenticationGSSContinue       AuthenticationGSSContinue
	authenticationSASL              AuthenticationSASL
	authenticationSASLContinue      AuthenticationSASLContinue
	authenticationSASLFinal         AuthenticationSASLFinal
	backendKeyData                  BackendKeyData
	bindComplete                    BindComplete
	closeComplete                   CloseComplete
	commandComplete                 CommandComplete
	copyBothResponse                CopyBothResponse
	copyData                        CopyData
	copyInResponse                  CopyInResponse
	copyOutResponse                 CopyOutResponse
	copyDone                        CopyDone
	dataRow                         DataRow
	emptyQueryResponse              EmptyQueryResponse
	errorResponse                   ErrorResponse
	functionCallResponse            FunctionCallResponse
	noData                          NoData
	noticeResponse                  NoticeResponse
	notificationResponse            NotificationResponse
	parameterDescription            ParameterDescription
	parameterStatus                 ParameterStatus
	parseComplete                   ParseComplete
	readyForQuery                   ReadyForQuery
	rowDescription                  RowDescription
	portalSuspended                 PortalSuspended

	bodyLen    int
	msgType    byte
	partialMsg bool
	authType   uint32
}

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

// Send sends a message to the backend (i.e. the server). The message is not guaranteed to be written until Flush is
// called.
//
// Send can work with any FrontendMessage. Some commonly used message types such as Bind have specialized send methods
// such as SendBind. These methods should be preferred when the type of message is known up front (e.g. when building an
// extended query protocol query) as they may be faster due to knowing the type of msg rather than it being hidden
// behind an interface.
func ( *Frontend) ( FrontendMessage) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceMessage('F', int32(len(.wbuf)-), )
	}
}

// Flush writes any pending messages to the backend (i.e. the server).
func ( *Frontend) () error {
	if len(.wbuf) == 0 {
		return nil
	}

	,  := .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 ( *Frontend) ( io.Writer,  TracerOptions) {
	.tracer = &tracer{
		w:             ,
		buf:           &bytes.Buffer{},
		TracerOptions: ,
	}
}

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

// SendBind sends a Bind message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Bind) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceBind('F', int32(len(.wbuf)-), )
	}
}

// SendParse sends a Parse message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Parse) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceParse('F', int32(len(.wbuf)-), )
	}
}

// SendClose sends a Close message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Close) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceClose('F', int32(len(.wbuf)-), )
	}
}

// SendDescribe sends a Describe message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Describe) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceDescribe('F', int32(len(.wbuf)-), )
	}
}

// SendExecute sends a Execute message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Execute) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.TraceQueryute('F', int32(len(.wbuf)-), )
	}
}

// SendSync sends a Sync message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Sync) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceSync('F', int32(len(.wbuf)-), )
	}
}

// SendQuery sends a Query message to the backend (i.e. the server). The message is not guaranteed to be written until
// Flush is called.
func ( *Frontend) ( *Query) {
	 := len(.wbuf)
	.wbuf = .Encode(.wbuf)
	if .tracer != nil {
		.tracer.traceQuery('F', int32(len(.wbuf)-), )
	}
}

// SendUnbufferedEncodedCopyData immediately sends an encoded CopyData message to the backend (i.e. the server). This method
// is more efficient than sending a CopyData message with Send as the message data is not copied to the internal buffer
// before being written out. The internal buffer is flushed before the message is sent.
func ( *Frontend) ( []byte) error {
	 := .Flush()
	if  != nil {
		return 
	}

	,  := .w.Write()
	if  != nil {
		return &writeError{err: , safeToRetry:  == 0}
	}

	if .tracer != nil {
		.tracer.traceCopyData('F', int32(len()-1), &CopyData{})
	}

	return nil
}

func translateEOFtoErrUnexpectedEOF( error) error {
	if  == io.EOF {
		return io.ErrUnexpectedEOF
	}
	return 
}

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

		.msgType = [0]

		 := int(binary.BigEndian.Uint32([1:]))
		if  < 4 {
			return nil, fmt.Errorf("invalid message length: %d", )
		}

		.bodyLen =  - 4
		.partialMsg = true
	}

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

	.partialMsg = false

	var  BackendMessage
	switch .msgType {
	case '1':
		 = &.parseComplete
	case '2':
		 = &.bindComplete
	case '3':
		 = &.closeComplete
	case 'A':
		 = &.notificationResponse
	case 'c':
		 = &.copyDone
	case 'C':
		 = &.commandComplete
	case 'd':
		 = &.copyData
	case 'D':
		 = &.dataRow
	case 'E':
		 = &.errorResponse
	case 'G':
		 = &.copyInResponse
	case 'H':
		 = &.copyOutResponse
	case 'I':
		 = &.emptyQueryResponse
	case 'K':
		 = &.backendKeyData
	case 'n':
		 = &.noData
	case 'N':
		 = &.noticeResponse
	case 'R':
		var  error
		,  = .findAuthenticationMessageType()
		if  != nil {
			return nil, 
		}
	case 's':
		 = &.portalSuspended
	case 'S':
		 = &.parameterStatus
	case 't':
		 = &.parameterDescription
	case 'T':
		 = &.rowDescription
	case 'V':
		 = &.functionCallResponse
	case 'W':
		 = &.copyBothResponse
	case 'Z':
		 = &.readyForQuery
	default:
		return nil, fmt.Errorf("unknown message type: %c", .msgType)
	}

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

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

	return , nil
}

// Authentication message type constants.
// See src/include/libpq/pqcomm.h for all
// constants.
const (
	AuthTypeOk                = 0
	AuthTypeCleartextPassword = 3
	AuthTypeMD5Password       = 5
	AuthTypeSCMCreds          = 6
	AuthTypeGSS               = 7
	AuthTypeGSSCont           = 8
	AuthTypeSSPI              = 9
	AuthTypeSASL              = 10
	AuthTypeSASLContinue      = 11
	AuthTypeSASLFinal         = 12
)

func ( *Frontend) ( []byte) (BackendMessage, error) {
	if len() < 4 {
		return nil, errors.New("authentication message too short")
	}
	.authType = binary.BigEndian.Uint32([:4])

	switch .authType {
	case AuthTypeOk:
		return &.authenticationOk, nil
	case AuthTypeCleartextPassword:
		return &.authenticationCleartextPassword, nil
	case AuthTypeMD5Password:
		return &.authenticationMD5Password, nil
	case AuthTypeSCMCreds:
		return nil, errors.New("AuthTypeSCMCreds is unimplemented")
	case AuthTypeGSS:
		return &.authenticationGSS, nil
	case AuthTypeGSSCont:
		return &.authenticationGSSContinue, nil
	case AuthTypeSSPI:
		return nil, errors.New("AuthTypeSSPI is unimplemented")
	case AuthTypeSASL:
		return &.authenticationSASL, nil
	case AuthTypeSASLContinue:
		return &.authenticationSASLContinue, nil
	case AuthTypeSASLFinal:
		return &.authenticationSASLFinal, nil
	default:
		return nil, fmt.Errorf("unknown authentication type: %d", .authType)
	}
}

// GetAuthType returns the authType used in the current state of the frontend.
// See SetAuthType for more information.
func ( *Frontend) () uint32 {
	return .authType
}

func ( *Frontend) () int {
	return .cr.wp - .cr.rp
}