summaryrefslogtreecommitdiff
path: root/server/lib/core/translation_service.dart
blob: 28dbdc26618ed6a6b9f1f9a0117d2017ec2962c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import 'dart:convert';
import 'dart:io';

import 'package:logging/logging.dart';

final _log = Logger('TranslationService');

/// In-game ability-text translations (the reference app's `TranslationService`,
/// disk-based port): loads `assets/i18n/<locale>.json` and resolves keys with
/// a fallback to the English key.
class TranslationService {
  Map<String, String> _translations = {};

  // Returns the translated string, or the English key if no translation exists.
  String t(String key) => _translations[key] ?? key;

  Future<void> load(String locale) async {
    if (locale == 'en') {
      _translations = {};
      return;
    }
    try {
      final file = File('assets/i18n/$locale.json');
      if (!file.existsSync()) {
        _log.warning(
          'TranslationService: locale file "$locale.json" not found',
        );
        _translations = {};
        return;
      }
      final jsonString = await file.readAsString();
      final Map<String, dynamic> data =
          jsonDecode(jsonString) as Map<String, dynamic>;
      final Map<String, String> flat = {};
      for (final entry in data.entries) {
        final value = entry.value;
        if (value is Map<String, dynamic>) {
          for (final inner in value.entries) {
            if (inner.value is String) {
              flat[inner.key] = inner.value as String;
            }
          }
        } else if (value is String) {
          flat[entry.key] = value;
        }
      }
      _translations = flat;
    } catch (e) {
      _log.warning('TranslationService: failed to load locale "$locale": $e');
      _translations = {};
    }
  }
}