import 'package:flyinsono/architecture/config/model.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/pages/setting/server_setting/view.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';

class ServerSettingState {
  final Rx<String> _currentAddress = Rx('');
  final Rx<String> _currentPort = Rx('');
  final Rx<String> _protocol = Rx(httpsProtocol);
  ServerOptionModel _appliedOption = ServerOptionModel.empty();

  ///协议
  String get protocol => _protocol.value;
  set protocol(String v) => _protocol.value = v;

  /// 选项集合
  final options = RxSet<ServerOptionModel>();

  /// 当前服务地址
  String get currentAddressName => _currentAddress.value;
  set currentAddressName(String val) {
    if (val != currentAddressName) {
      _currentAddress.value = val;
    }
  }

  /// 当前端口号
  String get currentPort => _currentPort.value;
  set currentPort(String val) {
    if (val != currentPort) {
      _currentPort.value = val;
    }
  }

  /// 已应用选项
  ServerOptionModel get appliedOption => _appliedOption;
  set appliedOption(ServerOptionModel val) {
    if (val != _appliedOption) {
      _appliedOption = val;
    }
    currentAddressName = val.disPlayName;
    currentPort = val.port;
  }
}

class ServerOptionModel {
  ServerOptionModel({
    required this.name,
    required this.host,
    required this.port,
    this.protocol = "http",
    this.isDefault = false,
  });

  factory ServerOptionModel.empty() {
    return ServerOptionModel(
      host: '',
      name: '',
      port: '',
    );
  }

  String name;
  String host;
  String port;
  String protocol;
  bool isDefault;

  String get fullAddress => isDefault ? DefaultServerName : uri.toString();

  Uri get uri => Uri(
        scheme: protocol,
        host: host,
        port: int.parse(port),
      );

  ///显示名称，用于服务器列表中切换
  String get disPlayName {
    if (isDefault) {
      if (kIsLab) {
        return '杏聆荟科研工作站';
      }
      return i18nBook.common.appName.t;
    }
    final portStr = uri.hasPort ? ":${uri.port}" : "";
    return '$host$portStr';
  }
}
