import 'dart:async';
import 'dart:convert' as convert;
import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/custom_model/Nursery.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
import 'package:farm_tpf/data/api/dio_provider.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:meta/meta.dart';

part 'action_detail_event.dart';
part 'action_detail_state.dart';

class ActionDetailBloc extends Bloc<ActionDetailEvent, ActionDetailState> {
  final Repository repository;
  ActionDetailBloc({required this.repository}) : super(ActionDetailInitial());
  final dio = DioProvider.instance();

  @override
  Stream<ActionDetailState> mapEventToState(
    ActionDetailEvent event,
  ) async* {
    if (event is FetchData) {
      if (!event.isNeedFetchData) {
        yield ActionDetailInitial();
      } else {
        try {
          yield ActionDetailLoading();
          Response<String> response = await dio.get("${ConstCommon.baseUrl}/${event.apiActivity}/${event.activityId}");
          final jsonData = json.decode(response.data ?? '');
          yield ActionDetailSuccess(item: jsonData);
        } catch (error) {
          yield ActionDetailFailure(errorString: AppException.handleError(error));
        }
      }
    }
  }
}
