import 'package:design/design.dart';
import 'package:flame/cache.dart';
import 'package:flame/flame.dart';
import 'package:guru_utils/visual_feast/visual_feast_aware.dart';
import 'package:guru_utils/visual_feast/engine/visual_feast_engine.dart';
import 'package:guru_utils/controller/lifecycle_controller.dart';
import 'package:guru_widgets/assetbar/guru_asset_bar.dart';
import 'package:guru_widgets/overlay/asset/asset_background.dart';
import 'package:guru_widgets/overlay/asset/asset_text.dart';
import 'package:guru_widgets/overlay/asset/asset_reward.dart';
import 'package:guru_utils/collection/collectionutils.dart';

class GuruAssetOverlayController extends LifecycleController
    with VisualFeastAware {
  VisualFeastEngine? engine;

  // Future loadGemsResource(VisualFeastEngine engine) async {
  //   final imageFutures = [
  //     Flame.images.load("ic_gem.png"),
  //   ];
  //   final loadedResources = await Future.wait([Future.wait(imageFutures)]);
  //   final images = loadedResources[0];
  //   addSprite("asset", VisualFeastSprite.fromImage(images[0]));
  // }

  void startClaim(int gems,
      {String scene = '',
      required GlobalKey key,
      bool useBg = true,
      VoidCallback? onCompleted,
      GuruAssetBarSizeSpec barSize = GuruAssetBarSizeSpec.s2,
      required String assetIcon}) async {
    await Future.delayed(const Duration(milliseconds: 200));
    engine ??= createEngine();
    
    final flameImage = Images(prefix: '');
    final imageFutures = [
      flameImage.load(assetIcon),
    ];
    final loadedResources = await Future.wait([Future.wait(imageFutures)]);
    final images = loadedResources[0];
    addSprite("asset", VisualFeastSprite.fromImage(images[0]));

    final background = AssetBackground(barSize, key, images[0]);
    final assetText = AssetText(gems);

    final gemsReward = AssetsReward(
      key,
      barSize,
      onFirstAssetComplete: () {
        claimGems(gems, scene);
      },
      onAllAssetsComplete: () async {
        background.hideBackground();
        await Future.delayed(const Duration(milliseconds: 650));
        onCompleted?.call();
      },
    );

    engine!.attachRenders(
        ListUtils.filterOutNulls([background, gemsReward, assetText]));

    dispatch(engine!);
  }

  Future claimGems(int gems, String scene) async {
    onClaimed(gems, scene);
  }

  void onClaimed(int gems, String scene) {}

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onInit() {
    super.onInit();
  }
}
