import 'dart:async';

import 'package:aitrainer_app/bloc/settings/settings_bloc.dart';
import 'package:aitrainer_app/service/firebase_api.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/session.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'session_event.dart';
part 'session_state.dart';

class SessionBloc extends Bloc<SessionEvent, SessionState> with Logging {
  final Session session;

  SessionBloc({required this.session}) : super(SessionInitial());

  @override
  Stream<SessionState> mapEventToState(
    SessionEvent event,
  ) async* {
    try {
      if (event is SessionStart) {
        log(" -------- Session starting...");
        yield SessionLoading();
        // ignore: close_sinks
        SettingsBloc settingsBloc = event.settingsBloc;
        await session.fetchSessionAndNavigate();
        FirebaseApi().setupRemoteConfig();
        String lang = AppLanguage().appLocal.languageCode;
        log("Change lang to $lang");
        settingsBloc.add(SettingsChangeLanguage(language: lang));
        yield SessionReady();
      }
    } on Exception catch (ex) {
      yield SessionFailure(message: ex.toString());
    }
  }

  @override
  Future<void> close() async {
    await this.close();
    super.close();
  }
}
