import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import '../../../../../model/passo/additional_items.dart';
import '../../../../../model/passo/building_and_structure.dart';
import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';

part 'building_and_structure_event.dart';
part 'building_and_structure_state.dart';

class BuildingAndStructureBloc
    extends Bloc<BuildingAndStructureEvent, BuildingAndStructureState> {
  BuildingAndStructureBloc() : super(BuildingAndStructureOfflineInitial()) {
    List<BldgAndStructure> bldgAndStructure = [];
    on<LoadBuildingAndStructure>((event, emit) async {
      emit(BuildingAndStructureOfflineInitial());
      try {
        emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure));
      } catch (e) {
        emit(BuildingAndStructureErrorState(e.toString()));
      }
    });
    on<LoadBuildingAndStructureEdit>((event, emit) async {
      emit(BuildingAndStructureOfflineInitial());
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getBuildingAndStructure(event.id);

      if (result.isNotEmpty) {
        bldgAndStructure =
            result.map((map) => BldgAndStructure.fromJson(map)).toList();

        emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure));
      } else {
        print('No data found.');
      }
    });

    on<AddBuildingAndStructure>((event, emit) async {
      try {
        BldgAndStructure item = await SQLServices.instance
            .createBuildingAndStructure(event.bldgAndStructure);

        print(item.toJson());

        bldgAndStructure.add(item);

        emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure));
      } catch (e) {
        print(e.toString());
      }
    });
    on<ShowBuildingAndStructure>((event, emit) async {
      emit(ShowBldgAndStructuresScreen());
    });
    on<FetchBuildingAndStructure>((event, emit) async {
      bldgAndStructure = await SQLServices.instance.readBuildingAndStructure();
      emit(BuildingAndStructureLoaded(bldgAndStructure: bldgAndStructure));
    });
    on<DeleteBuildingAndStructure>((event, emit) async {
      bldgAndStructure
          .removeWhere(((BldgAndStructure element) => element.id == event.id));
      await SQLServices.instance.deleteBuildingAndStructure(id: event.id);
      emit(const BuildingAndStructureDeletedState(success: true));
    });
  }
}
