import '../../models/attachment_media_type_enum.dart';
import '../../models/image_entry.dart';
import '../../models/media_attachment.dart';
import 'visibility_friendica_extensions.dart';

extension ImageEntryFriendicaExtension on ImageEntry {
  static ImageEntry fromJson(Map<String, dynamic> json) => ImageEntry(
      id: json['id'],
      album: json['album'],
      filename: json['filename'],
      description: json['desc'],
      thumbnailUrl: json['thumb'] ?? '',
      created: DateTime.tryParse(json['created']) ?? DateTime(0),
      height: json['height'],
      width: json['width'],
      visibility: VisibilityFriendicaExtensions.fromJson(json),
      scales: (json['scales'] as List<dynamic>? ?? [])
          .map((scaleJson) => _scaleFromJson(scaleJson))
          .toList());

  static ImageEntryScale _scaleFromJson(Map<String, dynamic> json) =>
      ImageEntryScale(
        id: json['id'].toString(),
        scale: json['scale'],
        link: Uri.parse(json['link']),
        width: json['width'],
        height: json['height'],
        size: json['size'],
      );

  MediaAttachment toMediaAttachment() {
    final thumbUri = Uri.parse(thumbnailUrl);
    final fullFileUri = scales.first.link;
    return MediaAttachment(
      id: id,
      uri: fullFileUri,
      fullFileUri: fullFileUri,
      creationTimestamp: created.millisecondsSinceEpoch,
      metadata: {},
      thumbnailUri: thumbUri,
      title: filename,
      explicitType: AttachmentMediaType.image,
      description: description,
      visibility: visibility,
    );
  }
}
