import 'dart:collection';
import 'dart:ui';

import 'package:guru_utils/log/log.dart';
import 'package:guru_utils/visual_feast/visual_feast_animation.dart';


/// Created by Haoyi on 2022/2/5

class VisualFeastObserver {
  final bool companion;
  final DoubleLinkedQueue<BaseVisualFeastAnimation> animations = DoubleLinkedQueue();
  final List<BaseVisualFeastAnimation> checkAnimations = [];
  final List<BaseVisualFeastAnimation> tempAnimations = [];
  final VoidCallback? onIdle;

  bool lastIsRunning = false;
  bool isRunning = false;

  VisualFeastObserver({this.onIdle}) : companion = false;

  VisualFeastObserver.companion({this.onIdle}) : companion = true;

  void add(BaseVisualFeastAnimation animation) {
    animations.add(animation);
  }

  bool update() {
    tempAnimations.clear();
    for (var animation in checkAnimations) {
      if (!animation.isCompleted) {
        tempAnimations.add(animation);
      }
    }
    while (animations.isNotEmpty) {
      final animation = animations.removeFirst();
      if (!animation.isCompleted) {
        tempAnimations.add(animation);
      }
    }
    checkAnimations.clear();
    checkAnimations.addAll(tempAnimations);
    lastIsRunning = isRunning;
    isRunning = checkAnimations.isNotEmpty;
    if (lastIsRunning != isRunning) {
      Log.e("hasRunningAnimation $isRunning");
      if (!isRunning) {
        onIdle?.call();
      }
    }
    return isRunning;
  }
}
