import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../common/constant/local_storage_key.dart';
import '../../domain/language/language.dart';
import '../../infrastructure/language/language.dart';

part 'language_event.dart';
part 'language_state.dart';
part 'language_bloc.freezed.dart';

@injectable
class LanguageBloc extends Bloc<LanguageEvent, LanguageState> {
  final SharedPreferences _prefs;
  LanguageBloc(this._prefs) : super(LanguageState.initial()) {
    on<LanguageEvent>(_onLanguageEvent);
  }

  Future<void> _onLanguageEvent(
    LanguageEvent event,
    Emitter<LanguageState> emit,
  ) async {
    switch (event) {
      case _ChangeLanguage(:final language):
        await _prefs.setString(
          LocalStorageKey.lang,
          language.locale.languageCode,
        );
        emit(state.copyWith(language: language));
        break;

      case _LoadLanguage():
        final selectedLanguage = _prefs.getString(LocalStorageKey.lang);

        final lang = languages.firstWhere(
          (item) => item.locale.languageCode == selectedLanguage,
          orElse: () => Language.indonesian(),
        );

        emit(
          state.copyWith(
            language: selectedLanguage != null ? lang : Language.indonesian(),
          ),
        );
        break;
    }
  }
}
