
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/languages_service.dart';

class AppLocalization {
  final Locale locale;

  AppLocalization(this.locale);

  static AppLocalization? of(BuildContext context) {
    return Localizations.of<AppLocalization>(context, AppLocalization);
  }

  Map<String?, String?> _localizedValues = {};

  //this is for local json reader
  // Future<bool> load() async {
  //   // Load the language JSON file from the "lang" folder
  //   String jsonString = await rootBundle.loadString('assets/i18n/${locale.languageCode}.json');
  //   Map<String, dynamic> jsonMap = json.decode(jsonString);
  //
  //   _localizedValues = jsonMap.map((key, value) {
  //     return MapEntry(key, value.toString());
  //   });
  //
  //   return true;
  // }

  Future load() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getString('token') != null){
      var languagesService = LanguagesService();
      var response = await languagesService.getLanguageValues(prefs.getInt('id')!);
      var result = json.decode(response.body.toString());
      Map<String, dynamic> mappedJson = result;
      _localizedValues =
          mappedJson.map((key, value) => MapEntry(key, value.toString()));

    }else{
      var languagesService0 = LanguagesService();
      var response = await languagesService0.getLanguage();
      var result = json.decode(response.body.toString());
      Map<String, dynamic> mappedJson = result;
      _localizedValues =
          mappedJson.map((key, value) => MapEntry(key, value.toString()));
    }
  }

  String? getTranslatedValue(String key) {
    if(_localizedValues[key] == null){
      return key;
    }else{
      return _localizedValues[key];
    }
  }

  saveTheTranslateValue(String key) async{
    var languagesService = LanguagesService();
 await languagesService.setTranslateValue(key);

  }



  static const LocalizationsDelegate<AppLocalization> delegate =
      _AppLocalizationDelegate();
}

class _AppLocalizationDelegate extends LocalizationsDelegate<AppLocalization> {
  const _AppLocalizationDelegate();

  @override
  bool isSupported(Locale locale) =>
      ['en', 'es','fr','hi','bn','id'].contains(locale.languageCode);

  @override
  Future<AppLocalization> load(Locale locale) async {
    AppLocalization appLocalization = AppLocalization(locale);
    await appLocalization.load();
    return appLocalization;
  }
  @override
  bool shouldReload(_AppLocalizationDelegate old) => false;
}
