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_boundaries.dart';
import 'package:unit2/model/passo/land_property_loc.dart';
import 'package:unit2/model/passo/land_property_owner.dart';
import 'package:unit2/sevices/passo/land/land_boundaries.dart';
import 'package:unit2/sevices/passo/land/land_location.dart';
import 'package:unit2/sevices/passo/land/land_property_owner.dart';
import 'package:http/http.dart' as http;
part 'land_property_owner_info_event.dart';
part 'land_property_owner_info_state.dart';

class LandPropertyOwnerInfoBloc
    extends Bloc<LandPropertyOwnerInfoEvent, LandPropertyOwnerInfoState> {
  LandPropertyOwnerInfoBloc() : super(LandLoading()) {
    on<LoadLand>((event, emit) async {
      emit(LandLoading());
      try {
        final faas = await LandServices.instance.fetch();
        emit(LandLoaded(faas));
      } catch (e) {
        emit(LandErrorState(e.toString()));
      }
    });
    on<AddPropertyOwnerLand>((event, emit) async {
      http.Response response = (await LandServices.instance.add(event.land))!;

      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        var details = jsonResponse['data']['details'];

        if (details != null) {
          var id = details['id'];
          final tempID = await SharedPreferences.getInstance();
          print(id);
          await tempID.setInt('landid', id + 1);
          final faas = await LandServices.instance.fetch();
          emit(LandLoaded(faas));
        } else {
          print("No 'details' object found in the response.");
          // Handle the case when 'details' is missing
        }
      }
    });

    on<UpdateLandLoc>((event, emit) async {
      final state = this.state;
      http.Response response = (await LandLocationService.instance
          .update(event.land_loc, event.land_loc.id))!;
      print('Land LOc');
      print(response.body);
    });

    on<UpdateLandBoundaries>((event, emit) async {
      final state = this.state;
      http.Response response = (await LandBoundariesService.instance
          .update(event.land_boundaries, event.land_boundaries.id))!;
      print('Land Boundaries');
      print(response.body);
    });
  }
}
