import 'package:logging/logging.dart';

import '../../globals.dart';
import '../../models/direct_message.dart';
import '../../services/auth_service.dart';
import '../../services/connections_manager.dart';
import '../../utils/active_profile_selector.dart';
import '../../utils/dateutils.dart';
import 'connection_friendica_extensions.dart';

final _logger = Logger('DirectMessageFriendicaExtension');

extension DirectMessageFriendicaExtension on DirectMessage {
  static DirectMessage fromJson(Map<String, dynamic> json) {
    final id = json['id'].toString();

    final senderId = json['sender_id'].toString();

    final senderScreenName = json['sender_screen_name'];

    final recipientId = json['recipient_id'].toString();

    final recipientScreenName = json['recipient_screen_name'];

    final title = json['title'];

    final text = json['text'];

    final createdAt = 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 bool seen = json['friendica_seen'];

    final String parentUri = json['friendica_parent_uri'];

    getIt<ActiveProfileSelector<ConnectionsManager>>()
        .activeEntry
        .andThenSuccess((cm) {
      if (getIt<AccountsService>().currentProfile.userId != senderId) {
        final s = ConnectionFriendicaExtensions.fromJson(json['sender']);
        cm.upsertConnection(s);
      }

      if (getIt<AccountsService>().currentProfile.userId != recipientId) {
        final r = ConnectionFriendicaExtensions.fromJson(json['recipient']);
        cm.upsertConnection(r);
      }
    });

    return DirectMessage(
      id: id,
      senderId: senderId,
      senderScreenName: senderScreenName,
      recipientId: recipientId,
      recipientScreenName: recipientScreenName,
      title: title,
      text: text,
      createdAt: createdAt,
      seen: seen,
      parentUri: parentUri,
    );
  }
}
