import 'dart:io';

import 'package:aitrainer_app/service/logging.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AppLanguage with Logging {
  static final AppLanguage _singleton = AppLanguage._internal();

  Locale? _appLocale = Locale('en');

  factory AppLanguage() {
    return _singleton;
  }

  AppLanguage._internal();

  static Future<AppLanguage> getInstance() async {
    return _singleton;
  }

  Locale get appLocal => _appLocale ?? Locale("en");

  Future<void> fetchLocale() async {
    var prefs = await SharedPreferences.getInstance();
    String? langCode = prefs.getString('language_code');
    log(" ---- lang code $langCode");
    if (langCode == null) {
      _appLocale = Locale('en');
    } else {
      _appLocale = Locale(langCode);
    }
    log(" ---- Fetched lang: " + _appLocale.toString());
  }

  getLocale(SharedPreferences prefs) {
    String? langCode = prefs.getString('language_code');
    if (langCode == null) {
      final String localName = Platform.localeName;
      if (localName.endsWith("HU")) {
        _appLocale = Locale('hu');
        langCode = "hu";
      } else {
        _appLocale = Locale('en');
        langCode = "en";
      }
    }
    _appLocale = Locale(langCode);
    log(" ---- Get lang: " + _appLocale.toString() + " lang code $langCode");
  }

  void changeLanguage(Locale type) async {
    var prefs = await SharedPreferences.getInstance();
    if (_appLocale == type) {
      return;
    }
    if (type == Locale("hu")) {
      _appLocale = Locale("hu");
      await prefs.setString('language_code', 'hu');
      await prefs.setString('countryCode', 'HU');
    } else {
      _appLocale = Locale("en");
      await prefs.setString('language_code', 'en');
      await prefs.setString('countryCode', 'US');
    }
    log(" ---- Stored lang: " + _appLocale.toString());
  }
}
