package codec

import (
	

	

	
)

const (
	// CodeAuthKeyNotFound means that specified auth key ID cannot be found by the DC.
	// Also, may be returned during key exchange.
	CodeAuthKeyNotFound = 404

	// CodeWrongDC means that current DC is wrong.
	// Usually returned by server when key exchange sends wrong DC ID.
	CodeWrongDC = 444

	// CodeTransportFlood means that too many transport connections are
	// established to the same IP in a too short lapse of time, or if any
	// of the container/service message limits are reached.
	CodeTransportFlood = 429
)

// ProtocolErr represents protocol level error.
type ProtocolErr struct {
	Code int32
}

func ( ProtocolErr) () string {
	switch .Code {
	case CodeAuthKeyNotFound:
		return "auth key not found"
	case CodeTransportFlood:
		return "transport flood"
	case CodeWrongDC:
		return "wrong DC"
	default:
		return fmt.Sprintf("protocol error %d", .Code)
	}
}

// Can be bigger that 1mb.
//
// See https://github.com/gotd/td/issues/412
//
// See https://github.com/tdlib/td/blob/550ccc8d9bbbe9cff1dc618aef5764d2cbd2cd91/td/mtproto/TcpTransport.cpp#L53
const maxMessageSize = 1 << 24 // 16 MB

func ( *bin.Buffer) error {
	 := .Len()
	if  > maxMessageSize ||  == 0 {
		return invalidMsgLenErr{n: }
	}
	return nil
}

func ( *bin.Buffer,  int) error {
	 := .Len()
	if % != 0 {
		return alignedPayloadExpectedErr{expected: }
	}
	return nil
}

func ( *bin.Buffer) error {
	if .Len() != bin.Word {
		return nil
	}
	,  := .Int32()
	if  != nil {
		return 
	}
	return &ProtocolErr{Code: -}
}

type alignedPayloadExpectedErr struct {
	expected int
}

func ( alignedPayloadExpectedErr) () string {
	return fmt.Sprintf("payload is not aligned, expected align by %d", .expected)
}

func ( alignedPayloadExpectedErr) ( error) bool {
	,  := .(alignedPayloadExpectedErr)
	return 
}

type invalidMsgLenErr struct {
	n int
}

func ( invalidMsgLenErr) () string {
	return fmt.Sprintf("invalid message length %d", .n)
}

func ( invalidMsgLenErr) ( error) bool {
	,  := .(invalidMsgLenErr)
	return 
}

// ErrProtocolHeaderMismatch means that received protocol header
// is mismatched with expected.
var ErrProtocolHeaderMismatch = errors.New("protocol header mismatch")