import '../../models/visibility.dart';

extension VisibilityFriendicaExtensions on Visibility {
  static Visibility fromJson(Map<String, dynamic> json) {
    final allowedUserIds = _parseAcl(json['allow_cid']);
    final excludedCircleIds = _parseAcl(json['deny_cid']);
    final allowedCircleIds = _parseAcl(json['allow_gid']);
    final excludedUserIds = _parseAcl(json['deny_cid']);
    final topLevelPrivate = json['friendica_private'];
    late final VisibilityType type;
    if (topLevelPrivate == null) {
      type = allowedUserIds.isEmpty &&
              excludedUserIds.isEmpty &&
              allowedCircleIds.isEmpty &&
              excludedCircleIds.isEmpty
          ? VisibilityType.public
          : VisibilityType.private;
    } else {
      type = topLevelPrivate ? VisibilityType.public : VisibilityType.private;
    }

    return Visibility(
      type: type,
      allowedUserIds: allowedUserIds,
      excludedUserIds: excludedUserIds,
      allowedCircleIds: allowedCircleIds,
      excludedCircleIds: excludedCircleIds,
    );
  }

  Map<String, String> toMapEntries() {
    return {
      'allow_cid': _idsListToAclString(allowedUserIds),
      'deny_cid': _idsListToAclString(excludedUserIds),
      'allow_gid': _idsListToAclString(allowedCircleIds),
      'deny_gid': _idsListToAclString(excludedCircleIds),
    };
  }

  static List<String> _parseAcl(String? acl) =>
      acl?.split(RegExp('[><]')).where((e) => e.isNotEmpty).toList() ?? [];

  String _idsListToAclString(List<String> ids) {
    return ids.map((id) => '<$id>').join('');
  }
}
