import 'package:fis_common/cross_platform_utils/utils.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flutter/foundation.dart';
import 'package:universal_html/html.dart' as html;

/// web工具
class AppWebUtils {
  static String? _currentSubTitle;
  static String? _websiteRootPath;

  /// 当前网站根目录
  static String get rootPath {
    _websiteRootPath ??= _findRootPath()!;
    return _websiteRootPath!;
  }

  /// 设置标题
  ///
  /// [title] 子标题，不填则仅设置主标题
  static Future<void> setTitle([String? subTitleKey]) async {
    if (!kIsWeb) return;
    final mainTitle = i18nBook.common.appName.t;
    await crossPlatformUtils.setTitle(mainTitle);
    _currentSubTitle = subTitleKey;
  }

  ///由于之前的FTrStr无法通过缓存的实力与当前国际化实例相通信。
  ///因此暂时没有办法通过统一的FTrStr进行subTitle的管理
  ///无论在翻译库里做，还是在主项目做，都需要管理一个subTitle的key
  ///因此决定在主项目引入该方法
  static String subTitleTr(String key) {
    switch (key) {
      case "homePage":
        return i18nBook.homePage.homePage.t;
      default:
        return "";
    }
  }

  /// 重新翻译标题
  static Future<void> retranslateTitle() async {
    await setTitle(_currentSubTitle);
  }

  static String? _findRootPath() {
    final baseURL = html.document.baseUri ?? html.window.location.origin;
    return baseURL;
    // final nodes = html.document.getElementsByTagName("script");
    // const tag = "canvaskit.js";
    // for (final node in nodes) {
    //   final script = node as html.ScriptElement;
    //   final index = script.src.indexOf(tag);
    //   if (index > -1) {
    //     return script.src.substring(0, index);
    //   }
    // }
    // return html.window.location.origin;
  }
}
