import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

class RemoteFileLoader extends AssetLoader {
  @override
  Future<Map<String, dynamic>?> load(String path, Locale locale) async {
    final directory = await getApplicationDocumentsDirectory();

    // easy_localization uses toLanguageTag() which gives 'en-US' or 'ar-SA'
    final fileName = "${locale.toLanguageTag()}.json";
    final file = File("${directory.path}/$fileName");

    if (await file.exists()) {
      final String jsonString = await file.readAsString();
      return jsonDecode(jsonString);
    } else {
      // If the download failed or hasn't happened yet, load from local assets
      // path is the 'path' property from the EasyLocalization widget
      final localData = await rootBundle.loadString('$path/$fileName');
      return jsonDecode(localData);
    }
  }
}
