import 'package:logging/logging.dart';

import '../../models/location_data.dart';
import '../../models/timeline_entry.dart';
import '../../models/visibility.dart';
import '../../utils/dateutils.dart';
import 'connection_friendica_extensions.dart';
import 'media_attachment_friendica_extensions.dart';

final _logger = Logger('FriendicaTimelineEntrySerializer');

extension TimelineEntryFriendicaExtensions on TimelineEntry {
  static TimelineEntry fromJson(Map<String, dynamic> json) {
    final int timestamp = json.containsKey('created_at')
        ? OffsetDateTimeUtils.epochSecTimeFromFriendicaString(
                json['created_at'])
            .fold(
                onSuccess: (value) => value,
                onError: (error) {
                  _logger.severe("Couldn't read date time string: $error");
                  return 0;
                })
        : 0;
    final id = json['id_str'] ?? '';
    final isReshare = json.containsKey('retweeted_status');
    final isPublic = !(json['friendica_private'] ?? false);
    final visibility = isPublic ? Visibility.public() : Visibility.private();
    final parentId = json['in_reply_to_status_id_str'] ?? '';
    final parentAuthor = json['in_reply_to_screen_name'] ?? '';
    final parentAuthorId = json['in_reply_to_user_id_str'] ?? '';
    final body = json['friendica_html'] ?? '';
    final author = json['user']['name'];
    final authorId = json['user']['id_str'];
    final title = json['friendica_title'] ?? '';
    final externalLink = json['external_url'] ?? '';
    const actualLocationData = LocationData();
    final modificationTimestamp = timestamp;
    final backdatedTimestamp = timestamp;
    final mediaAttachments = (json['attachments'] as List<dynamic>? ?? [])
        .map((j) => MediaAttachmentFriendicaExtensions.fromJson(j, visibility))
        .toList();
    final likes =
        (json['friendica_activities']?['like'] as List<dynamic>? ?? [])
            .map((json) => ConnectionFriendicaExtensions.fromJson(json))
            .toList();
    final dislikes =
        (json['friendica_activities']?['dislike'] as List<dynamic>? ?? [])
            .map((json) => ConnectionFriendicaExtensions.fromJson(json))
            .toList();

    return TimelineEntry(
      creationTimestamp: timestamp,
      modificationTimestamp: modificationTimestamp,
      backdatedTimestamp: backdatedTimestamp,
      locationData: actualLocationData,
      body: body,
      youReshared: isReshare,
      visibility: visibility,
      id: id,
      parentId: parentId,
      parentAuthorId: parentAuthorId,
      externalLink: externalLink,
      author: author,
      authorId: authorId,
      parentAuthor: parentAuthor,
      title: title,
      likes: likes,
      dislikes: dislikes,
      mediaAttachments: mediaAttachments,
    );
  }
}
