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_appr.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/sevices/passo/land/land_appraisal.dart';
part 'land_appraisal_event.dart';
part 'land_appraisal_state.dart';

class LandAppraisalBloc extends Bloc<LandAppraisalEvent, LandAppraisalState> {
  LandAppraisalBloc() : super(LandAppraisalLoading()) {
    List<LandAppr> globalLandAppraisal = [];
    on<LoadLandAppraisal>((event, emit) async {
      emit(LandAppraisalLoading());
      try {
        final tempID = await SharedPreferences.getInstance();
        print(tempID.getInt('landid'));
        final additionalItems =
            await LandAppraisalServices.instance.fetch(tempID.getInt('landid'));

        globalLandAppraisal
            .addAll(additionalItems); // Append all items to the list
        emit(LandAppraisalLoaded(globalLandAppraisal));
      } catch (e) {
        emit(LandAppraisalErrorState(e.toString()));
      }
    });
    on<LoadLandAppraisalEdit>((event, emit) async {
      emit(LandAppraisalLoading());
      try {
        final additionalItems =
            await LandAppraisalServices.instance.fetch(event.id);
        globalLandAppraisal.clear();
        globalLandAppraisal
            .addAll(additionalItems); // Append all items to the list
        emit(LandAppraisalLoaded(globalLandAppraisal));
      } catch (e) {
        emit(LandAppraisalErrorState(e.toString()));
      }
    });
    on<AddLandAppraisal>((event, emit) async {
      http.Response response =
          (await LandAppraisalServices.instance.add(event.land_appr))!;
      print(response.body);

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

        emit(LandAppraisalLoaded(globalLandAppraisal));
      }
    });
    on<DeleteLandAppraisal>((event, emit) async {
      print(event.id);
      http.Response response =
          (await LandAppraisalServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalLandAppraisal
            .removeWhere(((LandAppr element) => element.id == event.id));
        emit(LandAppraisalDeletedState(success: true));
      }
    });

    on<ShowLandAppraisal>((event, emit) async {
      emit(ShowAddLandAppraisalScreen());
    });
  }
}
