import 'package:fis_common/index.dart';
import 'package:flyinsono/architecture/app_parameters.dart';

const String DefaultServerName = "FLYINSONO";

///配置数据模型
class ConfigModel {
  ConfigModel({
    required this.common,
    required this.server,
    required this.flyinsonoServers,
  });

  _ServerModule server;
  List<String> flyinsonoServers;
  _CommonModule common;

  ///根据静态配置构造的词典创建配置数据模型实例
  factory ConfigModel.fromJson(Map<String, dynamic> map) {
    List<String> flyinsonoServers = [];
    if (map.containsKey('flyinsonoServers')) {
      final jsonList = map['flyinsonoServers'] as List<dynamic>;
      for (var f in jsonList) {
        flyinsonoServers.add(f);
      }
    } else {
      flyinsonoServers = AppParameters.data.flyinsonoServers;
    }
    return ConfigModel(
      common: _CommonModule.fromJson(map["common"] ?? {}),
      server: _ServerModule.fromJson(map['server'] ?? {}),
      flyinsonoServers: flyinsonoServers,
    );
  }

  ///将配置序列化成Json
  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {};
    map['common'] = common.toJson();
    map['server'] = server.toJson();
    map['flyinsonoServers'] = flyinsonoServers;
    return map;
  }
}

class _CommonModule {
  String dateTimeFormat;

  _CommonModule({
    required this.dateTimeFormat,
  });

  factory _CommonModule.fromJson(Map<String, dynamic> map) {
    return _CommonModule(
      dateTimeFormat: map['dateTimeFormat'] ?? "yyyy-MM-dd HH:mm",
    );
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {};
    map['dateTimeFormat'] = dateTimeFormat;
    return map;
  }
}

class _ServerModule {
  String? _current;
  Uri? _currentUri;

  /// 当前地址
  String? get current => _current;
  set current(String? value) {
    if (value != _current) {
      _currentUri = null;
      _current = value;
    }
  }

  /// 选项资源
  List<String> optionSource;

  _ServerModule({
    required String? currentUrl,
    required this.optionSource,
  }) {
    _current = currentUrl;
  }

  Uri? get currentUri {
    if (current.isNullOrEmpty || current == DefaultServerName) {
      return null;
    }
    if (_currentUri == null) {
      _currentUri = Uri.parse(current!);
    }
    return _currentUri!;
  }

  factory _ServerModule.fromJson(Map<String, dynamic> map) {
    List<String> options;
    if (map['optionSource'] != null) {
      options = (map['optionSource'] as List<dynamic>)
          .map((e) => e.toString())
          .toList();
    } else {
      options = [];
    }
    return _ServerModule(
      currentUrl: map['current'],
      optionSource: options,
    );
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {};
    if (current != null) {
      map['current'] = current;
    }
    map['optionSource'] = optionSource;
    return map;
  }
}
