import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';

import 'state.dart';

class ServerSettingController extends FControllerBase {
  final state = ServerSettingState();

  @override
  void onReady() {
    _load();
    super.onReady();
  }

  /// 保存配置
  Future<void> save() async {
    setBusy("正在保存");
    try {
      final uri = Uri(
        scheme: state.enableSSL ? "https" : "http",
        host: state.host,
        port: state.port,
      );
      final fullAddress = uri.toString();
      Store.app.serverUrl = fullAddress;
      await Store.persistent();

      //  更新RPC地址
      rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == 'https');
      rpc.clearCache();

      PromptBox.toast("保存成功");
    } catch (e) {
      logger.e("ServerSettingController save url error.", e);
      PromptBox.toast("保存失败");
    }
    cancelBusy();
  }

  void _load() async {
    final address = Store.app.serverUrl;
    final uri = Uri.parse(address);
    state.enableSSL = uri.scheme.toLowerCase() == "https";
    state.host = uri.host;
    state.port = uri.port;
  }
}
