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

class PropertyAssessmentEditBloc
    extends Bloc<PropertyAssessmentEditEvent, PropertyAssessmentEditState> {
  PropertyAssessmentEdit globalPropertyAssessmentEdit;
  PropertyAssessmentEditBloc()
      : globalPropertyAssessmentEdit = PropertyAssessmentEdit(),
        super(PropertyAssessmentEditInitial()) {
    on<LoadPropertyAssessmentEdit>((event, emit) async {
      emit(PropertyAssessmentEditLoading());
      try {
        final tempID = await SharedPreferences.getInstance();

        final assessments =
            await PropertyAssessmentServices.instance.fetchEdit(event.id);

        emit(PropertyAssessmentEditLoaded(assessments));
      } catch (e) {
        emit(PropertyAssessmentEditErrorState(e.toString()));
      }
    });
    on<AddPropertyAssessmentEdit>((event, emit) async {
      http.Response response = (await PropertyAssessmentServices.instance
          .addEdit(event.assessmentsEdit))!;
      print('Assessment');
      print(response.statusCode);
      print(response.body);
      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        PropertyAssessmentEdit newAssessment =
            PropertyAssessmentEdit.fromJson(jsonResponse['data']);

        globalPropertyAssessmentEdit = newAssessment;

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