import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart';

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

part 'other_improvements_event.dart';
part 'other_improvements_state.dart';

class OtherImprovementsBloc
    extends Bloc<OtherImprovementsEvent, OtherImprovementsState> {
  OtherImprovementsBloc() : super(OtherImprovementsInitial()) {
    List<OtherImprovements> otherImprovements = [];
    on<LoadOtherImprovements>((event, emit) async {
      emit(OtherImprovementsInitial());
      try {
        emit(OtherImprovementsLoaded(otherImprovements: otherImprovements));
      } catch (e) {
        emit(OtherImprovementsErrorState(e.toString()));
      }
    });
    on<LoadOtherImprovementsEdit>((event, emit) async {
      emit(OtherImprovementsInitial());
      List<Map<String, dynamic>> result =
          await SQLServices.instance.getOtherImprovements(event.id);

      if (result.isNotEmpty) {
        otherImprovements =
            result.map((map) => OtherImprovements.fromJson2(map)).toList();

        emit(OtherImprovementsLoaded(otherImprovements: otherImprovements));
      } else {
        print('No data found.');
      }
    });

    on<AddOtherImprovements>((event, emit) async {
      try {
        OtherImprovements item = await SQLServices.instance
            .createOtherImprovements(OtherImprovements(
                landapprDetailsId: event.landapprDetailsId,
                kindsOfTrees: event.kindsOfTrees,
                subclassAge: event.subclassAge,
                quantity: event.quantity,
                unitValue: event.unitValue,
                baseMarketval: event.baseMarketval,
                noOfProductive: event.noOfProductive,
                noOfNonproductive: event.noOfNonproductive,
                fruitBearing: event.fruitBearing));

        print(item.toJson());

        otherImprovements.add(item);

        emit(OtherImprovementsLoaded(otherImprovements: otherImprovements));
      } catch (e) {
        print(e.toString());
      }
    });
    on<ShowOtherImprovement>((event, emit) async {
      emit(ShowOtherImprovementScreen());
    });
    // on<FetchAdditionalItems>((event, emit) async {
    //   addItems = await SQLServices.instance.readAdditionalItems();
    //   emit(AdditionalItemsLoaded(addItem: addItems));
    // });
    on<DeleteOtherImprovements>((event, emit) async {
      otherImprovements
          .removeWhere(((OtherImprovements element) => element.id == event.id));
      await SQLServices.instance.deleteOtherImprovements(id: event.id);
      emit(const OtherImprovementsDeletedState(success: true));
    });
  }
}
