import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/product_detail_response.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/page/product_properties/product_properties.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class PropertiesCubit extends Cubit<ProductPropertiesState> {
  final AppRepository repository;
  DetailProductData? productData;

  //
  int isSelected = 0;

  PropertiesCubit(this.repository) : super(InitialProductPropertiesState());

  void getListProduct(int itemId) async {
    emit(ProductPropertiesLoading());
    ApiResult<DetailProductData> listProductResult = await repository.getProductDetail(itemId);
    listProductResult.when(success: (DetailProductData data) async {
      productData = data;
      // listSelectedIndex = List.filled(data.variants?.length ?? 0, 0);
      emit(ProductPropertiesSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(ProductPropertiesFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        DetailProductResponse productDetailResponse = DetailProductResponse.fromJson(await Util.parseJson("product.json"));
        productData = productDetailResponse.Data;
        //  listSelectedIndex = List.filled(productData?.variants?.length ?? 0, 0);
        emit(ProductPropertiesSuccess());
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void checkSelected(int index) {
    emit(ProductPropertiesLoading());
    this.isSelected = index;
    emit(ProductPropertiesSuccess());
  }
}
