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

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

part 'land_property_assessment_event.dart';
part 'land_property_assessment_state.dart';

class LandPropertyAssessmentBloc
    extends Bloc<LandPropertyAssessmentEvent, LandPropertyAssessmentState> {
  LandPropertyAssessmentBloc() : super(LandPropertyAssessmentInitial()) {
    List<LandPropertyAssessment> landPropertyAssessment = [];
    on<LoadLandPropertyAssessment>((event, emit) async {
      emit(LandPropertyAssessmentInitial());
      try {
        emit(LandPropertyAssessmentLoaded(
            landPropertyAssessment: landPropertyAssessment));
      } catch (e) {
        emit(LandPropertyAssessmentErrorState(e.toString()));
      }
    });
    on<LoadLandPropertyAssessmentEdit>((event, emit) async {
      emit(LandPropertyAssessmentInitial());
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getLandPropertyAssessment(event.id);

      if (result.isNotEmpty) {
        landPropertyAssessment =
            result.map((map) => LandPropertyAssessment.fromJson2(map)).toList();

        emit(LandPropertyAssessmentLoaded(
            landPropertyAssessment: landPropertyAssessment));
      } else {
        print('No data found.');
      }
    });

    on<AddLandPropertyAssessment>((event, emit) async {
      try {
        LandPropertyAssessment item = await SQLServices.instance
            .createLandPropertyAssessment(LandPropertyAssessment(
          landapprDetailsId: event.landapprDetailsId,
          actualUse: event.actualUse,
          marketval: event.marketval,
          assessmentLevel: event.assessmentLevel,
          assessedValue: event.assessedValue,
          totalMarketval: event.totalMarketval,
          totalAssessedval: event.totalAssessedval,
        ));

        print(item.toJson());

        landPropertyAssessment.add(item);

        emit(LandPropertyAssessmentLoaded(
            landPropertyAssessment: landPropertyAssessment));
      } catch (e) {
        print(e.toString());
      }
    });
    on<ShowLandPropertyAssessment>((event, emit) async {
      emit(ShowLandPropertyAssessmentcreen());
    });
    on<DeleteLandPropertyAssessment>((event, emit) async {
      landPropertyAssessment.removeWhere(
          ((LandPropertyAssessment element) => element.id == event.id));
      await SQLServices.instance.deleteLandPropertyAssessment(id: event.id);
      emit(const LandPropertyAssessmentDeletedState(success: true));
    });
  }
}
