import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums_and_consts/enums.dart';
import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart';

part 'theme_events.dart';
part 'theme_state.dart';

class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
  final SharedPreferences _prefs = GetIt.I.get<SharedPreferences>();
  ThemeBloc() : super(ThemeState(currentTheme: AppThemeMode.system)) {
    on<LoadThemeEvent>((event, emit) {
      emit(
        state.copyWith(
          currentTheme: AppThemeMode.fromValue(
            _prefs.getString(PrefKeys.theme.value),
          ),
        ),
      );
    });
    on<ChangeThemeEvent>((event, emit) async {
      await _prefs.setString(PrefKeys.theme.value, event.appThemeMode.value);
      emit(state.copyWith(currentTheme: event.appThemeMode));
    });
  }
}
