import '../../globals.dart';
import '../../models/connection.dart';
import '../../services/auth_service.dart';

extension ConnectionMastodonExtensions on Connection {
  static Connection fromJson(Map<String, dynamic> json,
      {String defaultServerName = ''}) {
    final name = json['display_name'] ?? '';
    final id = json['id']?.toString() ?? '';
    final profileUrl = Uri.parse(json['url'] ?? '');
    const network = 'Unknown';
    final avatar = Uri.tryParse(json['avatar_static'] ?? '') ?? Uri();
    final String handleFromJson = json['acct'];
    final String note = json['note'] ?? '';
    final int followersCount = json['followers_count'];
    final int followingCount = json['following_count'];
    final int statusesCount = json['statuses_count'];
    final lastStatus = DateTime.tryParse(json['last_status_at'] ?? '');

    late final String handle;
    if (handleFromJson.contains('@')) {
      handle = handleFromJson;
    } else {
      final server = defaultServerName.isNotEmpty
          ? defaultServerName
          : getIt<AccountsService>().currentProfile.serverName;
      handle = '$handleFromJson@$server';
    }

    return Connection(
      name: name,
      id: id,
      handle: handle,
      profileUrl: profileUrl.toString(),
      network: network,
      avatarUrl: avatar.toString(),
      note: note,
      followerCount: followersCount,
      followingCount: followingCount,
      statusesCount: statusesCount,
      lastStatus: lastStatus,
    );
  }
}
