import 'package:e_commerce_training/src/model/db/dbhelper.dart';
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/detail_product/detail_product_state.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/util/validator.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class DetailProductCubit extends Cubit<DetailProductState> with Validators {
  final AppRepository repository;
  DetailProductData? productData;
  final db = DatabaseHelper();
  int index = 0;
  bool check = true;

  DetailProductCubit(this.repository) : super(InitialDetailProductState());

  void getListProduct(int itemId, {bool isRefresh = false}) async {
    emit(isRefresh ? InitialDetailProductState() : DetailProductStateLoading());
    itemId = itemId;
    emit(DetailProductStateLoading());
    ApiResult<DetailProductData> listProductResult = await repository.getProductDetail(itemId);
    listProductResult.when(success: (DetailProductData data) async {
      productData = data;
      emit(GetListDetailProductSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(DetailProductFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        DetailProductResponse productDetailResponse =
            DetailProductResponse.fromJson(await Util.parseJson("product.json"));
        productData = productDetailResponse.Data;
        emit(GetListDetailProductSuccess());
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void checkLike() {
    emit(DetailProductStateLoading());
    this.check = !check;
    emit(GetListDetailProductSuccess());
  }

  void addProductDetailToCart() async {
    emit(InitialDetailProductState());
    productData = DetailProductData(
      itemId: productData!.itemId,
      image: productData!.image,
      vietnameseName: productData!.vietnameseName,
      englishName: productData!.englishName,
      price: productData!.price,
    );
    await db.addProduct(productData!);
    await Future.delayed(Duration(milliseconds: 100));
    emit(GetListDetailProductSuccess());
  }
}
