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

part 'land_property_assessment_event.dart';
part 'land_property_assessment_state.dart';

class LandPropertyAssessmentBloc
    extends Bloc<LandPropertyAssessmentEvent, LandPropertyAssessmentState> {
  LandPropertyAssessmentBloc() : super(LandPropertyAssessmentLoading()) {
    List<LandPropertyAssessment> globalLandPropertyAssessment = [];
    on<LoadLandPropertyAssessment>((event, emit) async {
      emit(LandPropertyAssessmentLoading());
      try {
        final tempID = await SharedPreferences.getInstance();
        print(tempID.getInt('landid'));
        final additionalItems = await LandPropertyAssessmentServices.instance
            .fetch(tempID.getInt('tempid'));

        globalLandPropertyAssessment
            .addAll(additionalItems); // Append all items to the list
        emit(LandPropertyAssessmentLoaded(globalLandPropertyAssessment));
      } catch (e) {
        emit(LandPropertyAssessmentErrorState(e.toString()));
      }
    });
    on<AddLandPropertyAssessment>((event, emit) async {
      http.Response response = (await LandPropertyAssessmentServices.instance
          .add(event.assessment))!;
      print(response.body);

      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        LandPropertyAssessment newAdditional =
            LandPropertyAssessment.fromJson(jsonResponse['data']);
        print(jsonResponse['data']);
        globalLandPropertyAssessment.add(newAdditional);

        emit(LandPropertyAssessmentLoaded(globalLandPropertyAssessment));
      }
    });
    on<DeleteLandPropertyAssessment>((event, emit) async {
      print(event.id);
      http.Response response =
          (await LandPropertyAssessmentServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalLandPropertyAssessment.removeWhere(
            ((LandPropertyAssessment element) => element.id == event.id));
        emit(LandPropertyAssessmentDeletedState(success: true));
      }
    });

    on<ShowLandPropertyAssessment>((event, emit) async {
      emit(ShowAddLandPropertyAssessmentScreen());
    });
  }
}
