import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/property_appraisal.dart';

import '../../../../../sevices/offline/offline_passo/admin/sql_services/sql_services.dart';

part 'bldg_appraisal_offline_event.dart';
part 'bldg_appraisal_offline_state.dart';

class BldgAppraisalOfflineBloc
    extends Bloc<BldgAppraisalOfflineEvent, BldgAppraisalOfflineState> {
  BldgAppraisalOfflineBloc() : super(BldgAppraisalOfflineInitial()) {
    List<PropertyAppraisal> appraisal = [];
    on<AddBldgAppraisal>((event, emit) async {
      await SQLServices.instance.createBldgAppraisal(PropertyAppraisal(
        id: event.id,
        bldgapprDetailsId: event.bldgapprDetailsId,
        assessedById: event.assessedById,
        assessedByName: event.assessedByName,
        dateCreated: event.dateCreated,
        dateModified: event.dateModified,
        unitconstructCost: event.unitconstructCost,
        buildingCore: event.buildingCore,
        unitconstructSubtotal: event.unitconstructSubtotal,
        depreciationRate: event.depreciationRate,
        depreciationCost: event.depreciationCost,
        costAddItems: event.costAddItems,
        addItemsSubtotal: event.addItemsSubtotal,
        totalpercentDepreciation: event.totalpercentDepreciation,
        marketValue: event.marketValue,
        totalArea: event.totalArea,
        actualUse: event.actualUse,
      ));
    });
    on<FetchSingleBldgAppraisal>((event, emit) async {
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getBldgAppraisal(event.id);

      if (result.isNotEmpty) {
        List<PropertyAppraisal> appraisalList =
            result.map((map) => PropertyAppraisal.fromJson2(map)).toList();

        // Choose a specific element from locationList
        PropertyAppraisal firstAppraisal = appraisalList
            .first; // You can change this to select a specific item

        print('appraisal test result');
        print(firstAppraisal.toJson());
        emit(SpecificBldgAppraisalLoaded(appraisal: firstAppraisal));
      } else {
        print('No data found.');
      }
    });
    on<UpdateAppraisal>((event, emit) async {
      await SQLServices.instance.updateAppraisal(event.id, event.appraisal);
    });
  }
}
