import 'package:bloc/bloc.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/preference/app_preference.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/list_page_response.dart';
import 'package:e_commerce_training/src/model/response/page_data.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/const.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:equatable/equatable.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';

part 'customer_support_state.dart';

class CustomerSupportCubit extends Cubit<CustomerSupportState> {
  final AppRepository repository;
  List<PageData> listPage = [];
  PackageInfo? packageInfo;
  String get version => packageInfo?.version ?? "";
  String get phoneNumber => appPreference.getData(Const.PHONE_NUMBER_SUPPORT) ?? "";
  CustomerSupportCubit(this.repository) : super(CustomerSupportInitial());
  void getVersion() async {
    emit(SupportLoading());
    packageInfo = await PackageInfo.fromPlatform();
    emit(CustomerSupportInitial());
  }

  void getListPage() async {
    emit(SupportLoading());
    ApiResult<List<PageData>> listPageResult = await repository.getListPage();
    listPageResult.when(success: (List<PageData> data) async {
      listPage = data;
      emit(SupportSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(SupportFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        ListPageResponse listPageResponse = ListPageResponse.fromJson(await Util.parseJson("list_page.json"));
        listPage = listPageResponse.data ?? [];
        emit(SupportSuccess());
      } catch (e) {
        logger.e(e);
        emit(SupportFailure(R.string.error.tr()));
      }
    });
  }
}
