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_ext.dart';
import 'package:unit2/sevices/passo/land/land_ext.dart';
import 'package:http/http.dart' as http;
part 'land_ext_event.dart';
part 'land_ext_state.dart';

class LandExtBloc extends Bloc<LandExtEvent, LandExtState> {
  LandExtBloc() : super(LandExtInitial()) {
    List<LandExt> globalLandExt = [];
    on<LoadLandExt>((event, emit) async {
      emit(LandExtLoading());
      try {
        final tempID = await SharedPreferences.getInstance();

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

        emit(LandExtLoaded(assessments));
      } catch (e) {
        emit(LandExtErrorState(e.toString()));
      }
    });
    on<AddLandExt>((event, emit) async {
      http.Response response =
          (await LandExtServices.instance.add(event.landext))!;
      print('landext');
      print(response.statusCode);
      print(response.body);
      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        LandExt newAssessment = LandExt.fromJson(jsonResponse['data']);

        globalLandExt.add(newAssessment);

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