import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/settings/bloc/settings_event.dart';
import 'package:hl_lieferservice/feature/settings/bloc/settings_state.dart';
import 'package:hl_lieferservice/feature/settings/model/settings.dart';
import 'package:hl_lieferservice/feature/settings/repository/settings_repository.dart';

class SettingsBloc extends Bloc<SettingsEvent, SettingsState> {
  SettingsRepository repository;

  SettingsBloc()
    : repository = SettingsRepository(),
      super(AppSettingsInitial()) {
    on<LoadSettings>(_load);
    on<UpdateSettings>(_update);
  }

  void _load(LoadSettings event, Emitter<SettingsState> emit) async {
    try {
      Settings settings = await repository.getSettings();
      debugPrint("use ${settings.useHardwareScanner}");
      emit(AppSettingsLoaded(settings: settings));
    } catch (e, st) {
      debugPrint("Failed to load settings: $e}");
      debugPrint("Stacktrace: ${st.toString()}");
      emit(AppSettingsFailed());
    }
  }

  void _update(UpdateSettings event, Emitter<SettingsState> emit) {
    try {
      repository.saveSettings(event.settings);
      emit(AppSettingsLoaded(settings: event.settings.copyWith()));
    } catch (e, st) {
      debugPrint("Failed to save settings: $e}");
      debugPrint("Stacktrace: ${st.toString()}");
      emit(AppSettingsFailed());
    }
  }
}
