package mtproto

import (
	
	

	
	

	
	
	
)

type badMessageError struct {
	Code    int
	NewSalt int64
}

const (
	codeMessageIDTooLow     = 16
	codeMessageIDTooHigh    = 17
	codeIncorrectServerSalt = 48
)

func ( badMessageError) () string {
	 := map[int]string{
		codeMessageIDTooLow:     "msg_id too low",
		codeMessageIDTooHigh:    "msg_id too high",
		codeIncorrectServerSalt: "incorrect server salt",

		18: "incorrect two lower order msg_id bits",
		19: "container msg_id is the same as msg_id of a previously received message",
		20: "message too old",
		32: "msg_seqno too low",
		33: "msg_seqno too high",
		34: "even msg_seqno expected, but odd received",
		35: "odd msg_seqno expected, but even received",
	}[.Code]
	if  == "" {
		return fmt.Sprintf("bad msg error code %d", .Code)
	}
	return 
}

// handleBadMsg handles bad_msg_notification and bad_server_salt received in
// the message msgID.
func ( *Conn) ( int64,  *bin.Buffer) error {
	,  := .PeekID()
	if  != nil {
		return 
	}
	switch  {
	case mt.BadMsgNotificationTypeID:
		var  mt.BadMsgNotification
		if  := .Decode();  != nil {
			return 
		}

		if .ErrorCode == codeMessageIDTooHigh && .serverTime != nil {
			// Our clock is ahead of the server's: take the server time from
			// the notification's own msg_id (not bad_msg_id, which is ours),
			// like TDLib (reset_server_time_difference) and Telegram Desktop.
			// For "too low" the offset was already raised from that msg_id
			// when it was received.
			.serverTime.reset(proto.MessageID().Time())
		}
		if .ErrorCode == codeMessageIDTooHigh {
			.log.Warn(context.Background(), "msg_id too high, starting a new session",
				log.Int64("bad_msg_id", .BadMsgID),
			)
			.failSession()
		}
		.rpc.NotifyError(.BadMsgID, &badMessageError{Code: .ErrorCode})
		return nil
	case mt.BadServerSaltTypeID:
		var  mt.BadServerSalt
		if  := .Decode();  != nil {
			return 
		}

		.rpc.NotifyError(.BadMsgID, &badMessageError{Code: .ErrorCode, NewSalt: .NewServerSalt})
		return nil
	default:
		return errors.Errorf("unknown type id %#x", )
	}
}