import 'package:flutter/material.dart';

import 'package:intl/find_locale.dart';

import 'package:shared_preferences/shared_preferences.dart';

import 'package:pshared/provider/locale.dart';


String _localeVarStorageName() {
  return 'mcrm_last_locale';
}

Locale _selectDefaultLocale(List<Locale> appLocales, Locale defaultLocale) {
  return appLocales.contains(defaultLocale) 
    ? defaultLocale 
    : appLocales.isEmpty 
      ? throw ArgumentError('empty application locales list', 'appLocales') 
      : appLocales.first;
}


class LocaleManager {
  late SharedPreferences _prefs;
  final List<Locale> appLocales;
  final Locale _defaultLocale;
  final LocaleProvider localeProvider;

  LocaleManager(this.localeProvider, this.appLocales, Locale defaultLocale) 
    : _defaultLocale = _selectDefaultLocale(appLocales, defaultLocale) {
    SharedPreferences.getInstance().then((prefs) {
      _prefs = prefs;
      _initializeLocaleProvider();
    });
  }

  Future<void> _initializeLocaleProvider() async {
    final initialLocale = await _getInitialLocale();
    localeProvider.setLocale(initialLocale);
    localeProvider.addListener(_onLocaleChanged);
  }

  Future<Locale> _getInitialLocale() async {
    final locale = await _pickLocale();
    return appLocales.contains(locale) ? locale : _defaultLocale;
  }

  Future<Locale> _pickLocale() async {
    String? savedLocaleCode = _prefs.getString(_localeVarStorageName());
    if (savedLocaleCode != null) {
      return Locale(savedLocaleCode);
    }

    String systemLocaleString = await findSystemLocale();
    final List<String> localeParts = systemLocaleString.split('_');
    final Locale systemLocale = Locale(localeParts[0]);

    final res = appLocales.contains(systemLocale);

    return res ? systemLocale : _defaultLocale;
  }

  Future<bool> saveLocale(Locale locale) async {
    return _prefs.setString(_localeVarStorageName(), locale.toString());
  }

  Future<bool> _onLocaleChanged() async {
    return saveLocale(localeProvider.locale);
  }
}