import 'package:bloc/bloc.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/category.dart';
import 'package:e_commerce_training/src/model/service/api_result.dart';
import 'package:e_commerce_training/src/model/service/network_exceptions.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import 'package:easy_localization/easy_localization.dart';

part 'category_state.dart';

class CategoryCubit extends Cubit<CategoryState> {
  final AppRepository repository;

  CategoryCubit(this.repository) : super(CategoryInitial());
  List<CategoryData> listCategory = [];

  //List<DataSubCategoryResponse>lisVitamin=[];
  int index = 0;
  int idFirst = 0;
  int count = 0;
  int selected = 0;

  List<int> countIndex = [];

  void onChangeCountIndex(int itemIndex) {
    if (this.countIndex.contains(itemIndex)) {
      emit(CategoryLoading());
      this.countIndex.remove(itemIndex);
      emit(CategoryInitial());
    } else {
      emit(CategoryLoading());
      this.countIndex.add(itemIndex);
      emit(CategoryInitial());
    }
  }

  void onChangeIndex(int index) {
    emit(CategoryLoading());
    this.index = index;
    this.countIndex = [];
    emit(CategoryInitial());
  }

  void onChangeFirst(int? id) {
    emit(CategoryLoading());
    this.idFirst = id!;
    emit(CategoryInitial());
  }

  void getCategory() async {
    emit(CategoryLoading());
    ApiResult<List<CategoryData>> categoryResult = await repository.getCategory();
    categoryResult.when(success: (List<CategoryData> data) async {
      listCategory = data;
      emit(GetCategorySuccess());
    }, failure: (NetworkExceptions error) async {
      emit(CategoryFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        CategoryResponse categoryResponse = CategoryResponse.fromJson(await Util.parseJson("category.json"));
        listCategory = categoryResponse.data ?? [];
        emit(GetCategorySuccess());
      } catch (e) {
        logger.e(e);
        emit(CategoryFailure(R.string.error.tr()));
      }
    });
  }
//
// void getSubCategory(int index)async{
//   ApiResult<List<CategorySubData>> listSubCategoryResult =
//   await repository.getListSubCategory(listSubCategoryData[index].listSubCategory![index].subId ?? 0,);
//   listSubCategoryResult.when(success: (List<CategorySubData> data) async {
//     listSubCategoryData[index] = data;
//     emit(GetCategorySuccess());
//   }, failure: (NetworkExceptions error) {  }
// }

}
