import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/additional_items.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/sevices/passo/building/additional_items_services.dart';

part 'additional_item_event.dart';
part 'additional_item_state.dart';

class AdditionalItemBloc
    extends Bloc<AdditionalItemEvent, AdditionalItemState> {
  AdditionalItemBloc() : super(AdditionalItemsLoading()) {
    List<AdditionalItems> globalAdditionalItems = [];
    on<LoadAdditionalItems>((event, emit) async {
      emit(AdditionalItemsLoading());
      try {
        // final tempID = await SharedPreferences.getInstance();
        // print(tempID.getInt('tempid'));
        // final additionalItem = await GetAdditionalItems.getAdditionalItems(
        //     tempID.getInt('tempid'));

        emit(AdditionalItemsLoaded(globalAdditionalItems));
      } catch (e) {
        emit(AdditionalItemsErrorState(e.toString()));
      }
    });
    on<AddAdditionalItems>((event, emit) async {
      emit(AdditionalItemsLoading());
      try {
        http.Response response =
            (await AdditionalItemsServices.instance.add(event.items))!;
        print(response.body);

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

          emit(AdditionalItemsLoaded(globalAdditionalItems));
        } else {
          emit(AdditionalItemsErrorState('error'));
        }
      } catch (e) {
        emit(AdditionalItemsErrorState(e.toString()));
      }
    });
    on<DeleteAdditionalItems>((event, emit) async {
      print(event.id);
      http.Response response =
          (await AdditionalItemsServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalAdditionalItems
            .removeWhere(((AdditionalItems element) => element.id == event.id));
        emit(AdditionalItemsDeletedState(success: true));
      }
    });

    on<ShowAdditionalItems>((event, emit) async {
      emit(ShowAddItemsScreen());
    });
  }
}
