import 'package:food_delivery_client/food_delivery_client.dart';

part 'theme_event.dart';

part 'theme_state.dart';

part 'theme_bloc.freezed.dart';

@injectable
class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
  final StorageService _storageService;

  ThemeBloc(this._storageService) : super(const ThemeState()) {
    on<_Started>(_onStarted);
    on<_Changed>(_onChanged);
  }

  void _onStarted(_Started event, Emitter<ThemeState> emit) {
    final isDark = _storageService.getBool(key: AppLocaleKeys.theme);

    if (isDark) {
      emit(state.copyWith(themeMode: ThemeMode.dark));
    } else {
      emit(state.copyWith(themeMode: ThemeMode.light));
    }
  }

  void _onChanged(_Changed event, Emitter<ThemeState> emit) {
    if (state.themeMode == ThemeMode.light) {
      _storageService.setBool(key: AppLocaleKeys.theme, value: true);
      emit(state.copyWith(themeMode: ThemeMode.dark));
    } else {
      _storageService.setBool(key: AppLocaleKeys.theme, value: false);
      emit(state.copyWith(themeMode: ThemeMode.light));
    }
  }
}
