import 'dart:async';

import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/util/app_localization.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/util/track.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';

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

class SettingsBloc extends Bloc<SettingsEvent, SettingsState> with Logging {
  String? language;
  Locale? _locale;
  BuildContext? context;

  SettingsBloc({this.context}) : super(SettingsInitial()) {
    on<SettingsChangeLanguage>(_onChangeLanguage);
    on<SettingsGetLanguage>(_onGetLanguage);
    on<SettingsSetServer>(_onSetServer);
  }

  void setLocale(Locale locale) => _locale = locale;
  Locale? getLocale() => _locale;

  void _onChangeLanguage(SettingsChangeLanguage event, Emitter<SettingsState> emit) async {
    emit(SettingsLoading());
    await _changeLang(event.language);
    emit(SettingsReady());
  }

  void _onGetLanguage(SettingsGetLanguage event, Emitter<SettingsState> emit) async {
    await AppLanguage().fetchLocale();
    _locale = AppLanguage().appLocal;
    emit(SettingsReady());
  }

  void _onSetServer(SettingsSetServer event, Emitter<SettingsState> emit) async {
    final bool live = event.live;
    Cache().setServer(live);
    Track().track(TrackingEvent.settings_server, eventValue: live.toString());
  }

  Future<void> _changeLang(String lang) async {
    log("_change to $lang");
    switch (lang) {
      case "English":
      case "en":
      case "Angol":
        _locale = Locale('en');
        break;
      case "Hungarian":
      case "Magyar":
      case "hu":
        _locale = Locale('hu');
        break;
    }
    this.language = lang;
    AppLanguage().changeLanguage(_locale!);
    await loadLang();
    Cache().initBadges();
  }

  Future<void> loadLang() async {
    if (_locale != null) {
      log(" -- Loading lang $_locale");
      if (context != null) {
        AppLocalizations.of(context!)!.setLocale(_locale!);
        await AppLocalizations.of(context!)!.load();
      } else {
        log("no context, does not load");
      }
    } else {
      log("no locale, does not load");
    }
  }
}
