import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rasadyar_core/core.dart';

class SliderLogic extends GetxController with StateMixin<List<String>> {
  final PageController pageController = PageController(initialPage: 0, viewportFraction: .93);
  late Timer _timer;
  late Duration duration;

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

    duration = Duration(seconds: randomInt(8, 18));
  }

  void _startSliding(int itemCount) {
    _timer = Timer.periodic(duration, (timer) {
      if (pageController.hasClients) {
        int nextPage = pageController.page!.round() + 1;
        if (nextPage == itemCount) {
          nextPage = 0;
        }
        pageController.animateToPage(
          nextPage,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeIn,
        );
      }
    });
  }

  @override
  void onClose() {
    _timer.cancel();
    pageController.dispose();
    super.onClose();
  }

  void onSuccess(List<String> data) {
    change(data, status: RxStatus.success());
    _startSliding(data.length);
  }
}
