import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart';
import 'package:unit2/model/passo/land_value_adjustment.dart';

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

part 'value_adjustment_event.dart';
part 'value_adjustment_state.dart';

class ValueAdjustmentBloc
    extends Bloc<ValueAdjustmentEvent, ValueAdjustmentState> {
  ValueAdjustmentBloc() : super(ValueAdjustmentInitial()) {
    List<ValueAdjustments> valueAdjustment = [];
    on<LoadValueAdjustment>((event, emit) async {
      emit(ValueAdjustmentInitial());
      try {
        emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment));
      } catch (e) {
        emit(ValueAdjustmentErrorState(e.toString()));
      }
    });
    on<LoadValueAdjustmentEdit>((event, emit) async {
      emit(ValueAdjustmentInitial());
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getValueAdjustments(event.id);

      if (result.isNotEmpty) {
        valueAdjustment =
            result.map((map) => ValueAdjustments.fromJson2(map)).toList();

        emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment));
      } else {
        print('No data found.');
      }
    });

    on<AddValueAdjustments>((event, emit) async {
      try {
        ValueAdjustments item =
            await SQLServices.instance.createValueAdjustments(ValueAdjustments(
          landapprDetailsId: event.landapprDetailsId,
          baseMarketval: event.baseMarketval,
          adjustmentFactors: event.adjustmentFactors,
          adjustment: event.adjustment,
          valueAdjustment: event.valueAdjustment,
          marketValue: event.marketValue,
        ));

        print(item.toJson());

        valueAdjustment.add(item);

        emit(ValueAdjustmentLoaded(valueAdjustment: valueAdjustment));
      } catch (e) {
        print(e.toString());
      }
    });
    on<ShowValueAdjustment>((event, emit) async {
      emit(ShowValueAdjustmentcreen());
    });
    on<DeleteValueAdjustment>((event, emit) async {
      valueAdjustment
          .removeWhere(((ValueAdjustments element) => element.id == event.id));
      await SQLServices.instance.deleteValueAdjustment(id: event.id);
      emit(const ValueAdjustmentDeletedState(success: true));
    });
  }
}
