class FriendicaEntry {
  final Map<String, dynamic> originalJson;
  final int id;
  final String text;
  final String url;
  final int commentCount;
  final List<String> images;

  FriendicaEntry(
      {required this.originalJson,
      required this.text,
      required this.id,
      required this.commentCount,
      required this.url,
      required this.images});

  FriendicaEntry.fromJson(Map<String, dynamic> json)
      : originalJson = json,
        id = json['id'] ?? -1,
        text = json['text'] ?? '',
        url = json['external_url'] ?? '',
        commentCount = _commentCountFromJson(json),
        images = _imagesFromJson(json);

  @override
  String toString() {
    return '''
    FriendicaPost{
      id: $id, 
      text: $text, 
      url: $url,
      commentCount: $commentCount,
      images: $images,
    }
    ''';
  }

  static int _commentCountFromJson(Map<String, dynamic> json) {
    final readCount = json['friendica_comments'] ?? 0;
    final count = readCount is int ? readCount : int.tryParse(readCount) ?? 0;
    return count;
  }

  static List<String> _imagesFromJson(Map<String, dynamic> json) {
    final List<dynamic> attachments = json['attachments'] ?? [];
    return attachments
        .where((a) => a['mimetype']?.startsWith('image') ?? false)
        .map((a) => a['url']?.toString() ?? '')
        .where((urlString) => urlString.isNotEmpty)
        .toList();
  }
}
