import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/setting_bloc/setting_event.dart';
import 'package:syncrow_web/pages/routines/bloc/setting_bloc/setting_state.dart';
import 'package:syncrow_web/pages/routines/models/icon_model.dart';
import 'package:syncrow_web/services/routines_api.dart';

class SettingBloc extends Bloc<SettingEvent, SettingState> {
  bool isExpanded = false;
  String selectedIcon = '';
  List<IconModel> iconModelList = [];

  SettingBloc() : super(const InitialState()) {
    on<InitialEvent>(_initialSetting);
    on<FetchIcons>(_fetchIcons);
    on<SelectIcon>(_selectIcon);
  }

  void _initialSetting(InitialEvent event, Emitter<SettingState> emit) async {
    try {
      emit(const LoadingState());
      selectedIcon = event.selectedIcon;
      emit(TabToRunSettingLoaded(
          showInDevice: true, selectedIcon: event.selectedIcon, iconList: iconModelList));
    } catch (e) {
      emit(const FailedState(error: 'Something went wrong'));
    }
  }

  void _fetchIcons(FetchIcons event, Emitter<SettingState> emit) async {
    try {
      isExpanded = event.expanded;
      emit(const LoadingState());
      if (isExpanded) {
        iconModelList = await SceneApi.getIcon();
        emit(TabToRunSettingLoaded(
            showInDevice: true, selectedIcon: selectedIcon, iconList: iconModelList));
      }
    } catch (e) {
      emit(const FailedState(error: 'Something went wrong'));
    }
  }

  void _selectIcon(SelectIcon event, Emitter<SettingState> emit) async {
    try {
      emit(const LoadingState());
      selectedIcon = event.iconId;
      emit(TabToRunSettingLoaded(
          showInDevice: true, selectedIcon: event.iconId, iconList: iconModelList));
    } catch (e) {
      emit(const FailedState(error: 'Something went wrong'));
    }
  }
}
