import 'dart:collection';

import 'package:flutter/cupertino.dart';

import 'package:yumi/ui_kit/widgets/room/anim/l_gift_animal_view.dart';

class GiftAnimationManager extends ChangeNotifier {
  Queue<LGiftModel> pendingAnimationsQueue = Queue<LGiftModel>();
  List<LGiftScrollingScreenAnimsBean> animationControllerList = [];

  //每个控件正在播放的动画
  Map<int, LGiftModel?> giftMap = {0: null, 1: null, 2: null, 3: null};

  void enqueueGiftAnimation(LGiftModel giftModel) {
    pendingAnimationsQueue.add(giftModel);
    proceedToNextAnimation();
  }

  ///开始播放
  proceedToNextAnimation() {
    if (pendingAnimationsQueue.isEmpty) {
      return;
    }
    var playGift = pendingAnimationsQueue.first;
    for (var key in giftMap.keys) {
      var value = giftMap[key];
      if (value == null) {
        giftMap[key] = playGift;
        pendingAnimationsQueue.removeFirst();
        notifyListeners();
        animationControllerList[key].controller.forward(from: 0);
        break;
      } else {
        if (value.labelId == playGift.labelId) {
          playGift.giftCount = value.giftCount + playGift.giftCount;
          giftMap[key] = playGift;
          pendingAnimationsQueue.removeFirst();
          notifyListeners();
          animationControllerList[key].controller.forward(from: 0.45);
          break;
        }
      }
    }
  }

  void attachAnimationControllers(List<LGiftScrollingScreenAnimsBean> anins) {
    animationControllerList = anins;
  }

  void cleanupAnimationResources() {
    pendingAnimationsQueue.clear();
    giftMap[0] = null;
    giftMap[1] = null;
    giftMap[2] = null;
    giftMap[3] = null;
    for (var element in animationControllerList) {
      element.controller.dispose();
    }
  }

  void markAnimationAsFinished(int index) {
    giftMap[index] = null;
    notifyListeners();
    proceedToNextAnimation();
  }
}
