import 'dart:convert';
import 'dart:ui';

import 'package:devicelocale/devicelocale.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:trans_lark/entity/language_entity.dart';
import 'package:trans_lark/generated/assets.dart';
import 'package:trans_lark/util/num_util.dart';

class TranslateManager {
  TranslateManager._();

  static final TranslateManager _instance = TranslateManager._();

  factory TranslateManager() {
    return _instance;
  }

  /// 支持翻译的所有语言
  var languageList = <LanguageEntity>[].obs;

  /// 源语言
  var fromLanguageEntity = LanguageEntity(
    languageCode: 'en',
    languageName: 'English',
  ).obs;

  /// 目标语言
  var toLanguageEntity = LanguageEntity(
    languageCode: 'zh-cn',
    languageName: 'Chinese (Simplified)',
  ).obs;

  /// 是否选择的源语言
  var isSelectFromLanguage = true.obs;

  Future<void> init() async {
    var data = jsonDecode(await rootBundle.loadString(Assets.jsonLanguage));
    if (data != null && data is List) {
      languageList.value = data.map((e) => LanguageEntity.fromMap(e)).toList();
    }

    List<Locale> languages = await Devicelocale.preferredLanguagesAsLocales;
    if (languages.isNotEmpty) {
      var languageEntity = languageList.firstWhereOrNull((e) => e.languageCode.contains(languages[0].languageCode));
      if (languageEntity != null) {
        toLanguageEntity.value = languageEntity.copyWith();
      }
      if (toLanguageEntity.value.languageCode == fromLanguageEntity.value.languageCode) {
        var index = 0;
        for (var i = 0; i < languageList.length; ++i) {
          var o = languages[i];
          if (o.languageCode == toLanguageEntity.value.languageCode) {
            index = i;
            break;
          }
        }
        var num = NumUtil.getRandomNumberExcludingCurrent(0, languageList.length, index);
        fromLanguageEntity.value = languageList[num].copyWith();
      }
    }
  }
}
