private fun groupMessages(messages: List<Message>,isInThread: Boolean,reads: List<ChannelUserRead>,): List<MessageListItemState> {val parentMessageId =(messageMode as? MessageMode.MessageThread)?.parentMessage?.idval currentUser = user.valueval groupedMessages = mutableListOf<MessageListItemState>()val lastRead = reads.filter { it.user.id != currentUser?.id }.mapNotNull { it.lastRead }.maxOrNull() messages.forEachIndexed { index, message ->val user = message.user val previousMessage = messages.getOrNull(index - 1) val nextMessage = messages.getOrNull(index + 1) val previousUser = previousMessage?.user val nextUser = nextMessage?.user val willSeparateNextMessage = nextMessage?.let { shouldAddDateSeparator(message, it) } ?: false  val position = when { previousUser != user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Top previousUser == user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Middle previousUser == user && nextUser != user -> MessageItemGroupPosition.Bottom else -> MessageItemGroupPosition.None }  val isLastMessageInGroup = position == MessageItemGroupPosition.Bottom || position == MessageItemGroupPosition.None  val shouldShowFooter = messageFooterVisibility.shouldShowMessageFooter( message = message, isLastMessageInGroup = isLastMessageInGroup, nextMessage = nextMessage )  if (shouldAddDateSeparator(previousMessage, message)) { groupedMessages.add(DateSeparatorState(message.getCreatedAtOrThrow())) }  if (message.isSystem() || message.isError()) { groupedMessages.add(SystemMessageState(message = message)) } else { val isMessageRead = message.createdAt ?.let { lastRead != null && it <= lastRead } ?: false  groupedMessages.add( MessageItemState( message = message, currentUser = currentUser, groupPosition = position, parentMessageId = parentMessageId, isMine = user.id == currentUser?.id, isInThread = isInThread, isMessageRead = isMessageRead, shouldShowFooter = shouldShowFooter, deletedMessageVisibility = deletedMessageVisibility ) ) }  if (index == 0 && isInThread) { groupedMessages.add(ThreadSeparatorState(message.replyCount)) } }  return groupedMessages.reversed() }
Takes in the available messages for a [Channel] and groups them based on the sender ID. We put the message in a group, where the positions can be [MessageItemGroupPosition.Top], [MessageItemGroupPosition.Middle],  [MessageItemGroupPosition.Bottom] or [MessageItemGroupPosition.None] if the message isn't in a group.