import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/services/entity/default_entry_setting.dart';
import 'package:flyinsono/architecture/services/modules/default_entry_configuration.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/js_platform/methods.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

import 'base.dart';

class ThesaurusChangeHandler extends MethodHandlerBase {
  ThesaurusChangeHandler() : super(TargetMethodName.ThesaurusChange);

  @override
  Future<void> execute(List<String> args) async {
    /// 默认词条持久化缓存服务
    late final DefaultEntryService defaultEntryService =
        Get.find<DefaultEntryService>();

    DefaultEntrySetting defaultEntrySetting = DefaultEntrySetting.ins;
    var token = args[0];
    Store.user.setToken(token);
    final defaultThesaurus = await rpc.report.getDefaultThesaurusContentAsync(
      GetDefaultThesaurusContentRequest(
        token: Store.user.token,
        languageCode: i18nBook.locale.toCodeString('-'),
      ),
    );
    var baseInfo = defaultThesaurus.baseInfo;
    if (baseInfo != null) {
      var thesaurusCode = baseInfo.thesaurusCode ?? '';
      if (thesaurusCode.isNotEmpty) {
        final getThesaurusItemsAsync = await rpc.report.getThesaurusItemsAsync(
          GetThesaurusItemsRequest(
            token: Store.user.token,
            thesaurusCode: thesaurusCode,
          ),
        );
        if (getThesaurusItemsAsync.isEmpty)
          return;
        else {
          defaultEntrySetting
              .setDefaultEntry(jsonEncode(getThesaurusItemsAsync));
          defaultEntryService.save();
        }
      }
    }
  }
}
