import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/property_appraisal_edit.dart';
import 'package:unit2/sevices/passo/building/property_appraisal_services.dart';
import 'package:http/http.dart' as http;

part 'property_appraisal_edit_event.dart';
part 'property_appraisal_edit_state.dart';

class PropertyAppraisalEditBloc
    extends Bloc<PropertyAppraisalEditEvent, PropertyAppraisalEditState> {
  PropertyAppraisalEditBloc() : super(PropertyAppraisalEditLoading()) {
    on<LoadPropertyAppraisalEdit>((event, emit) async {
      emit(PropertyAppraisalEditLoading());
      try {
        final appraisalEdit =
            await PropertyAppraisalServices.instance.fetchEdit(event.id);
        emit(PropertyAppraisalEditLoaded(appraisalEdit));
      } catch (e) {
        emit(PropertyAppraisalEditErrorState(e.toString()));
      }
    });
    on<UpdatePropertyAppraisalEdit>((event, emit) async {
      http.Response response = (await PropertyAppraisalServices.instance
          .updateAppraisal(event.appraisalEdit!, event.id))!;

      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        PropertyAppraisalEdit newAppraisal =
            PropertyAppraisalEdit.fromJson(jsonResponse['data']);
        print(response.statusCode);
        emit(PropertyAppraisalEditLoaded(newAppraisal));

        // emit(PropertyAppraisalLoaded(globalPropertyAppraisal));
      }
    });
  }
}
