import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart';
import 'package:unit2/model/passo/land_appr.dart';

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

part 'land_property_appraisal_event.dart';
part 'land_property_appraisal_state.dart';

class LandPropertyAppraisalBloc
    extends Bloc<LandPropertyAppraisalEvent, LandPropertyAppraisalState> {
  LandPropertyAppraisalBloc() : super(LandPropertyAppraisalInitial()) {
    List<LandAppr> landAppr = [];
    on<LoadLandPropertyAppraisal>((event, emit) async {
      emit(LandPropertyAppraisalInitial());
      try {
        emit(LandPropertyAppraisalLoaded(landAppr: landAppr));
      } catch (e) {
        emit(LandPropertyAppraisalErrorState(e.toString()));
      }
    });
    on<LoadLandPropertyAppraisalEdit>((event, emit) async {
      emit(LandPropertyAppraisalInitial());
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getLandPropertyAppraisal(event.id);

      if (result.isNotEmpty) {
        landAppr = result.map((map) => LandAppr.fromJson2(map)).toList();

        emit(LandPropertyAppraisalLoaded(landAppr: landAppr));
      } else {
        print('No data found.');
      }
    });

    on<AddLandPropertyAppraisal>((event, emit) async {
      try {
        print(event);
        LandAppr item = await SQLServices.instance.createLandAppraisal(LandAppr(
            landapprDetailsId: event.landapprDetailsId,
            classification: event.classification,
            subClass: event.subClass,
            area: event.area,
            unitValue: event.unitValue,
            baseMarketval: event.baseMarketval));

        print('Appraisal');
        print(item.toJson());

        landAppr.add(item);

        emit(LandPropertyAppraisalLoaded(landAppr: landAppr));
      } catch (e) {
        print(e.toString());
      }
    });
    on<ShowAdditionalItems>((event, emit) async {
      emit(ShowAddItemsScreen());
    });
    // on<FetchAdditionalItems>((event, emit) async {
    //   addItems = await SQLServices.instance.readAdditionalItems();
    //   emit(AdditionalItemsLoaded(addItem: addItems));
    // });
    on<DeleteLandPropertyAppraisal>((event, emit) async {
      landAppr.removeWhere(((LandAppr element) => element.id == event.id));
      await SQLServices.instance.deleteLandPropertyAppraisal(id: event.id);
      emit(const LandPropertyAppraisalDeletedState(success: true));
    });
  }
}
