import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';

import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/data_sources/sources/local/data_persistence.dart';

class LocalizationManager with ChangeNotifier {
  Locale? _locale;

  Locale? get locale => _locale;

  LocalizationManager() {
    _locale = _resolveInitialLocale();
    if (_locale != null) {
      SCGlobalConfig.lang = _locale!.languageCode;
    }
  }

  Locale _resolveInitialLocale() {
    String language = DataPersistence.getLang();
    if (language.isEmpty) {
      Locale systemLocale = ui.PlatformDispatcher.instance.locale;
      if (systemLocale.languageCode.startsWith("ar")) {
        return const Locale('ar', '');
      } else if (systemLocale.languageCode == "en") {
        return const Locale('en', '');
      } else if (systemLocale.languageCode == "tr") {
        return const Locale('tr', '');
      } else if (systemLocale.languageCode == "bn") {
        return const Locale('bn', '');
      } else {
        return const Locale('en', '');
      }
    } else {
      if (language.startsWith("ar")) {
        return const Locale('ar', '');
      } else if (language == "tr") {
        return const Locale('tr', '');
      } else if (language == "bn") {
        return const Locale('bn', '');
      } else {
        return const Locale('en', '');
      }
    }
  }

  void changeAppLanguage(Locale locale) {
    if (_locale?.languageCode == locale.languageCode &&
        _locale?.countryCode == locale.countryCode) {
      return;
    }
    _locale = locale;
    SCGlobalConfig.lang = locale.languageCode;
    unawaited(DataPersistence.setLang(locale.languageCode));
    notifyListeners();
  }
}
