import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/device_manager_bloc/device_manager_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/device_manager_bloc/device_manager_event.dart';
import 'package:syncrow_app/features/scene/bloc/tab_change/tab_change_event.dart';
import 'package:syncrow_app/features/scene/bloc/tab_change/tab_change_state.dart';

class TabBarBloc extends Bloc<TabBarEvent, TabBarState> {
  TabBarBloc(this.deviceManagerBloc) : super(const TabBarInitialState()) {
    on<TabBarTabChangedEvent>(_onTabBarTabChangedEvent);
  }

  final DeviceManagerBloc deviceManagerBloc;

  void _onTabBarTabChangedEvent(
    TabBarTabChangedEvent event,
    Emitter<TabBarState> emit,
  ) {
    _getDevices(event);

    emit(
      TabBarTabSelectedState(
        roomId: event.roomId,
        selectedTabIndex: event.selectedIndex,
      ),
    );
  }

  void _getDevices(TabBarTabChangedEvent event) {
    if (event.roomId == "-1") {
      deviceManagerBloc.add(FetchAllDevices());
    } else {
      deviceManagerBloc.add(FetchDevicesByRoomId(event.roomId, event.unit));
    }
  }
}
