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_assessment.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/sevices/passo/building/property_assessment_services.dart';

part 'property_assessment_event.dart';
part 'property_assessment_state.dart';

class PropertyAssessmentBloc
    extends Bloc<PropertyAssessmentEvent, PropertyAssessmentState> {
  PropertyAssessmentBloc() : super(PropertyAssessmentInitial()) {
    List<PropertyAssessment> globalPropertyAssessment = [];
    on<LoadPropertyAssessment>((event, emit) async {
      emit(PropertyAssessmentLoading());
      try {
        final tempID = await SharedPreferences.getInstance();

        final assessments = await PropertyAssessmentServices.instance
            .fetch(tempID.getInt('tempid')! + 1);

        emit(PropertyAssessmentLoaded(assessments));
      } catch (e) {
        emit(PropertyAssessmentErrorState(e.toString()));
      }
    });
    on<AddPropertyAssessment>((event, emit) async {
      http.Response response =
          (await PropertyAssessmentServices.instance.add(event.assessments))!;
      print('Assessment');
      print(response.statusCode);
      print(response.body);
      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        PropertyAssessment newAssessment =
            PropertyAssessment.fromJson(jsonResponse['data']);

        globalPropertyAssessment.add(newAssessment);

        emit(PropertyAssessmentLoaded(globalPropertyAssessment));
      }
    });
    on<UpdatePropertyAssessment>((event, emit) async {
      final tempID = await SharedPreferences.getInstance();
      final tempID2 = tempID.getInt('tempid')! - 1;
      http.Response response = (await PropertyAssessmentServices.instance
          .update(event.assessment, tempID2))!;
      print('assessment');
      print(response.statusCode);
      print(response.body);
      // if (response.statusCode == 201) {
      //   final faas = await PropertyInfoRepository.getUsers();
      //   emit(FaasLoaded(faas));
      // }
    });
  }
}
