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

import '../../../../../sevices/offline/offline_passo/admin/api_services/municipalities_api_services.dart';

part 'municipalities_admin_event.dart';
part 'municipalities_admin_state.dart';

class MunicipalitiesAdminBloc
    extends Bloc<MunicipalitiesAdminEvent, MunicipalitiesAdminState> {
  MunicipalitiesAdminBloc() : super(MunicipalitiesAdminInitial()) {
    List<City> city = [];
    on<LoadMunicipalities>((event, emit) async {
      city = await SQLServices.instance.readAllMunicipalities();

      emit(MunicipalitiesLoaded(city: city));
    });
    //  on<MunicipalitiesSyncToDevice>((event, emit) async {
    //   try {
    //             final result =
    //                 await MunicipalityAdminApiServices.instance.fetch();

    //             // Assuming result is a List of JSON objects, convert them to City objects.
    //             final cities =
    //                 result.map((json) => City.fromJson(json)).toList();

    //             // Loop through the list of City objects and insert them into the local database.
    //             for (City city in cities) {
    //               print(city.cityDescription);
    //               print(city.cityCode);
    //               await SQLServices.instance.createMunicipalities(city);
    //             }
    //           } catch (e) {
    //             // Handle any errors that might occur during the API call or database insertion.
    //             print("Error: $e");
    //           }

    //   // emit(const LoadMunicipalities());
    // });
    on<AddMunicipality>((event, emit) async {
      await SQLServices.instance.createMunicipalities(
        City(
          id: event.id,
          cityCode: event.cityCode,
          cityDescription: event.cityDescription,
        ),
      );
    });
  }
}
