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

import '../../../../../model/passo/structural_materials_ii.dart';
import '../../../../../model/passo/structureMaterial.dart';
import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';

part 'structural_material_offline_event.dart';
part 'structural_material_offline_state.dart';

class StructuralMaterialOfflineBloc extends Bloc<StructuralMaterialOfflineEvent,
    StructuralMaterialOfflineState> {
  StructuralMaterialOfflineBloc() : super(StructuralMaterialOfflineInitial()) {
    List<StructureMaterials> materials = [];
    on<AddStructuralMaterial>((event, emit) async {
      await SQLServices.instance.createStructuralMaterials(StructureMaterialsII(
          id: event.id,
          bldgapprDetailsId: event.bldgapprDetailsId,
          foundation: event.foundation!.join(', ').split(', '),
          columns: event.columns!.join(', ').split(', '),
          beams: event.beams!.join(', ').split(', '),
          trussFraming: event.trussFraming!.join(', ').split(', '),
          roof: event.roof!.join(', ').split(', '),
          flooring: event.flooring!.join(', ').split(', '),
          walls: event.walls!.join(', ').split(', '),
          others: event.others!.join(', ').split(', '),
          genCode: event.genCode,
          assessedById: event.assessedById,
          assessedByName: event.assessedByName,
          dateCreated: event.dateCreated,
          dateModified: event.dateModified));
    });
    on<FetchSingleStructuralMaterial>((event, emit) async {
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getStructuralMaterials(event.id);

      if (result.isNotEmpty) {
        List<StructureMaterials> materialList =
            result.map((map) => StructureMaterials.fromJson2(map)).toList();

        // Choose a specific element from locationList
        StructureMaterials firstMaterial =
            materialList.first; // You can change this to select a specific item

        print('struct mat test result');
        print(firstMaterial);
        emit(SpecificStructuralMaterialLoaded(materials: firstMaterial));
      } else {
        print('No data found.');
      }
    });
    on<UpdateStructuralMaterials>((event, emit) async {
      await SQLServices.instance
          .updateStructuralMaterial(event.id, event.materials);
    });
  }
}
