import 'dart:async';

import 'package:flutter/material.dart';

import 'lottie_widget.dart';


class LottieController {
  final AnimationController animationController;
  final LottieAction lottieAction;
  final LottieUpdateCallback? updateCallback;
  final double repeatMin;
  final double repeatMax;
  final Duration duration;
  final Duration period;
  final VoidCallback? completedCallback;
  final Duration delayed;
  Timer? _delayedTimer;

  LottieController(this.animationController, this.lottieAction, this.updateCallback, this.repeatMin,
      this.repeatMax, this.duration, this.period, this.completedCallback, this.delayed) {
    animationController.duration = duration;
    animationController.addListener(onUpdate);
    animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        onComplete();
      }
    });
  }

  void forward({double from = 0.0}) {
    if (delayed.inMilliseconds > 0) {
      _delayedTimer?.cancel();
      _delayedTimer = Timer(delayed, () {
        animationController.forward(from: 0.0);
      });
    } else {
      animationController.forward(from: 0.0);

    }
  }

  void repeat() {
    animationController.repeat(min: repeatMin, max: repeatMax, period: period);
  }

  void stop({bool canceled = false}) {
    animationController.stop(canceled: canceled);
    _delayedTimer?.cancel();
  }

  void reverse({double from = 1}) {
    animationController.reverse(from: from);
  }

  void onUpdate() {
    updateCallback?.call(animationController.value);
  }

  void dispose() {
    _delayedTimer?.cancel();
    animationController.dispose();
  }

  void onComplete() {
    switch (lottieAction) {
      case LottieAction.forwardAndRepeat:
        animationController.repeat(min: repeatMin, max: repeatMax, period: period);
        break;
      default:
        break;
    }
  }
}

class DefaultLottieController extends LottieController {
  DefaultLottieController(TickerProvider tickerProvider,
      {double repeatMin = 0.0,
      double repeatMax = 1.0,
      LottieAction lottieAction = LottieAction.none,
      Duration duration = const Duration(milliseconds: 800),
      Duration period = const Duration(milliseconds: 800),
      LottieUpdateCallback? updateCallback,
      VoidCallback? completedCallback,
      Duration delayDuration = const Duration(milliseconds: 0)})
      : super(AnimationController(vsync: tickerProvider), lottieAction, updateCallback, repeatMin,
            repeatMax, duration, period, completedCallback, delayDuration);
}
