import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/sevices/offline/offline_passo/admin/sql_services/sql_services.dart';

import '../../../../../model/passo/bldg_loc.dart';

part 'location_event.dart';
part 'location_state.dart';

class LocationBloc extends Bloc<LocationEvent, LocationState> {
  LocationBloc() : super(LocationInitial()) {
    List<BldgLoc> todos = [];
    on<AddLocation>((event, emit) async {
      await SQLServices.instance.createBldglocation(BldgLoc(
          id: event.id,
          bldgapprDetailsId: event.bldgapprDetailsId,
          assessedById: event.assessedById,
          assessedByName: event.assessedByName,
          street: event.street,
          barangay: event.barangay,
          municipality: event.municipality,
          province: event.province,
          genCode: event.genCode));
    });
    on<FetchSingleLocation>((event, emit) async {
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getLocation(event.id);

      if (result.isNotEmpty) {
        List<BldgLoc> locationList =
            result.map((map) => BldgLoc.fromJson(map)).toList();

        // Choose a specific element from locationList
        BldgLoc firstLocation =
            locationList.first; // You can change this to select a specific item

        print('location test result');
        print(firstLocation);
        emit(SpecificLocationLoaded(location: firstLocation));
      } else {
        print('No data found.');
      }
    });
    on<UpdateBldgLoc>((event, emit) async {
      await SQLServices.instance.updateLocation(event.id, event.bldgLoc);
    });
  }
}
