import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:initial_folder/models/carts_model.dart';
import 'package:initial_folder/services/cart_service.dart';

enum ResultState { Loading, NoData, HasData, Error }

class CartsProvider with ChangeNotifier {
  final CartService cartService;
  CartsProvider({required this.cartService}) {
    getCarts();
  }

  CartsModel? _cartsModel;
  CartsModel? get result => _cartsModel;

  ResultState? _state;
  ResultState? get state => _state;

  String _message = '';
  String _finalPrice = '';

  String get message => _message;
  String get finalPrice => _finalPrice;

  int _length = 0;
  int get lenght => _length;

  set lengthCarts(int v) {
    _length = v;
    notifyListeners();
  }

  List _data = [];
  List get data => _data;

  // StreamController<List<DataCartsModel>> dataStream = StreamController.broadcast();

  set carts(CartsModel carts) {
    _cartsModel = carts;
    notifyListeners();
  }

  void clear() {
    _length = 0;
    notifyListeners();
  }

  Future<dynamic> getCarts() async {
    try {
      _state = ResultState.Loading;
      _data = [];
      notifyListeners();
      CartsModel carts = await cartService.getCarts();
      _length = carts.data.length;
      notifyListeners();
      if (carts.data.isEmpty) {
        _state = ResultState.NoData;
        notifyListeners();
        return _message = 'Empty Data';
      } else {
        _data = carts.data.map((e) => e.courseId).toList();
        _state = ResultState.HasData;
        print(_data);
        print("ini dari getcatsrs");
        notifyListeners();
        return _cartsModel = carts;
      }
    } catch (e) {
      _state = ResultState.Error;
      log('$e');
      notifyListeners();
      return _message = 'Error --> $e';
    }
  }
}
