import 'dart:async';

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

part 'device_activity_event.dart';
part 'device_activity_state.dart';

class DeviceActivityBloc extends Bloc<DeviceActivityEvent, DeviceActivityState> {
  final Repository repository;
  DeviceActivityBloc({required this.repository}) : super(DeviceActivityInitial());

  @override
  Stream<DeviceActivityState> mapEventToState(
    DeviceActivityEvent event,
  ) async* {
    if (event is DataFetched) {
      try {
        final response = await repository.getDeviceForActivity();
        var devices = response.map((device) {
          if (device.id == event.selectedId) {
            device.isSelected = true;
          }
          return device;
        }).toList();
        yield DeviceActivitySuccess(items: devices);
      } catch (_) {
        yield DeviceActivityFailure();
      }
    } else if (event is OnRefresh) {
      try {
        final response = await repository.getDeviceForActivity();
        var devices = response.map((device) {
          if (device.id == event.selectedId) {
            device.isSelected = true;
          }
          return device;
        }).toList();
        yield DeviceActivitySuccess(items: devices);
      } catch (_) {
        yield DeviceActivityFailure();
      }
    }
  }
}
