import 'dart:convert';

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

part 'property_appraisal_event.dart';
part 'property_appraisal_state.dart';

class PropertyAppraisalBloc
    extends Bloc<PropertyAppraisalEvent, PropertyAppraisalState> {
  PropertyAppraisalBloc() : super(PropertyAppraisalInitial()) {
    List<PropertyAppraisal> globalPropertyAppraisal = [];
    on<LoadPropertyAppraisal>((event, emit) async {
      emit(PropertyAppraisalLoading());
      try {
        final appraisal = await PropertyAppraisalServices.instance.fetch();
        print(appraisal);
        emit(PropertyAppraisalLoaded(appraisal));
      } catch (e) {
        emit(PropertyAppraisalErrorState(e.toString()));
      }
    });
    on<AddPropertyAppraisal>((event, emit) async {
      final tempID = await SharedPreferences.getInstance();
      emit(PropertyAppraisalLoading());
      try {
        http.Response response = (await PropertyAppraisalServices.instance
            .update(event.appraisal, tempID.getInt('tempid')! - 1))!;
        print('Appraisal');
        print(tempID.getInt('tempid')! - 1);
        print(event.appraisal.toJson());
        print(response.body);
        if (response.statusCode == 200) {
          emit(ShowPropertyAppraisalSuccessAlertState());
        }
      } catch (e) {
        print('app error');
        print(e.toString());
        emit(ShowPropertyAppraisalErrorAlertState());
      }
    });
  }
}
