reorderChat method

Future<void> reorderChat(
  1. int from,
  2. int to
)

Reorders a Chat from the from position to the to position.

Implementation

Future<void> reorderChat(int from, int to) async {
  final List<ChatEntry> favorites =
      chats
          .where(
            (e) =>
                e.chat.value.ongoingCall == null &&
                e.chat.value.favoritePosition != null &&
                !e.chat.value.isHidden &&
                !e.hidden.value,
          )
          .toList();

  double position;

  if (to <= 0) {
    position = favorites.first.chat.value.favoritePosition!.val * 2;
  } else if (to >= favorites.length) {
    position = favorites.last.chat.value.favoritePosition!.val / 2;
  } else {
    position =
        (favorites[to].chat.value.favoritePosition!.val +
            favorites[to - 1].chat.value.favoritePosition!.val) /
        2;
  }

  if (to > from) {
    to--;
  }

  final int start = chats.indexOf(favorites[from]);
  final int end = chats.indexOf(favorites[to]);

  final ChatId chatId = chats[start].id;
  chats.insert(end, chats.removeAt(start));

  await favoriteChat(chatId, ChatFavoritePosition(position));
}