import '../models/entry_tree_item.dart';
import '../models/flattened_tree_item.dart';

extension FlatteningExtensions on EntryTreeItem {
  static const BaseLevel = 0;

  List<FlattenedTreeItem> flatten(
      {int level = BaseLevel, bool topLevelOnly = false}) {
    final items = <FlattenedTreeItem>[];
    final myEntry = FlattenedTreeItem(
      timelineEntry: entry,
      isMine: isMine,
      level: level,
    );

    items.add(myEntry);
    if (topLevelOnly) {
      return items;
    }

    final sortedChildren = [...children];
    sortedChildren.sort((c1, c2) =>
        c1.entry.creationTimestamp.compareTo(c2.entry.creationTimestamp));
    for (final child in sortedChildren) {
      int childLevel = level + 1;
      if (child.entry.authorId == entry.authorId && level != BaseLevel) {
        childLevel = level;
      }

      final childItems = child.flatten(level: childLevel);
      childItems.sort((c1, c2) {
        if (c2.level == c1.level) {
          return c1.timelineEntry.creationTimestamp
              .compareTo(c2.timelineEntry.creationTimestamp);
        }

        if (c1.level == childLevel) {
          return -1;
        }

        if (c2.level == childLevel) {
          return 1;
        }

        return 0;
      });

      items.addAll(childItems);
    }

    return items;
  }
}
