import 'dart:async';

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krezus/repositories/metadata/metadata_repository.dart';
import 'package:krezus/repositories/metadata/models/settings.dart';

part 'settings_event.dart';
part 'settings_state.dart';

class SettingsBloc extends Bloc<SettingsEvent, SettingsState> {
  final MetadataRepository _metadataRepository;

  SettingsBloc({required MetadataRepository metadataRepository}) : _metadataRepository = metadataRepository, super(const SettingsState()) {
    on<SettingsLoad>(_onSettingsLoad);
    on<SetThemeMode>(_onSetThemeMode);

    _metadataRepository
      .getSettingsStream()
      .listen((settings) => add(SettingsLoad(settings)));
  }

  FutureOr<void> _onSettingsLoad(SettingsLoad event, Emitter<SettingsState> emit) {
    emit(state.copyWith(
      themeMode: event.settings.themeMode,
    ));
  }

  FutureOr<void> _onSetThemeMode(SetThemeMode event, Emitter<SettingsState> emit) {
    _metadataRepository.saveSettings(Settings(themeMode: event.themeMode));
    emit(state.copyWith(
      themeMode: event.themeMode,
    ));
  }
}
