import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/custom_model/action_form/CommonData.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:meta/meta.dart';

part 'common_data_event.dart';
part 'common_data_state.dart';

class CommonDataBloc extends Bloc<CommonDataEvent, CommonDataState> {
  final Repository repository;
  CommonDataBloc({required this.repository}) : super(CommonDataInitial());

  @override
  Stream<CommonDataState> mapEventToState(
    CommonDataEvent? event,
  ) async* {
    if (event is DataFetched) {
      try {
        final response = await repository.getCommonData(
          tableSupply: event.tbSupply ?? '',
          condition: event.condition ?? '',
        );
        List<CommonData> commonDatas = response.map((data) {
          if (data.id == event.selectedId) {
            data.isSelected = true;
          }
          return data;
        }).toList();

        yield CommonDataSuccess(items: commonDatas);
      } catch (_) {
        yield CommonDataFailure();
      }
    } else if (event is OnRefresh) {
      try {
        final response = await repository.getCommonData(
          tableSupply: event.tbSupply ?? '',
          condition: event.condition ?? '',
        );
        List<CommonData> commonDatas = response.map((data) {
          if (data.id == event.selectedId) {
            data.isSelected = true;
          }
          return data;
        }).toList();

        yield CommonDataSuccess(items: commonDatas);
      } catch (_) {
        yield CommonDataFailure();
      }
    }
  }
}
