import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../app.dart';

class MyCarouselController extends GetxController {
  RxList<SliderModel> sliders = <SliderModel>[].obs;
  RxList<SliderModel> banners = <SliderModel>[].obs;

  final pageController = PageController(keepPage: false);

  // RxInt currentPage = 0.obs;
  int _currentPage = 0;

  RxBool isSliderLoading = true.obs;

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

  Future<void> _getSliders() async {
    isSliderLoading.value = true;
    final resultSliders = await SliderApi.get();

    if (resultSliders.length == 0) {
      isSliderLoading.value = false;
      return;
    }

    for (var i = 0; i < resultSliders.length - 1; i++) {
      if (resultSliders[i].type == 'slider') {
        sliders.add(resultSliders[i]);
      } else {
        banners.add(resultSliders[i]);
      }
    }

    isSliderLoading.value = false;

    changeBanner();
  }

  void changeBanner() {
    debugPrint('changeBanner');
    Timer.periodic(Duration(seconds: 5), (Timer timer) {
      if (_currentPage < sliders.length - 1) {
        _currentPage++;
      } else {
        _currentPage = 0;
      }

      if (pageController.hasClients) {
        pageController.animateToPage(
          _currentPage,
          duration: Duration(milliseconds: 350),
          curve: Curves.easeIn,
        );
      }
    });
  }

  void onPageChanged(int currPage) {
    _currentPage = currPage;
  }
}
