import 'dart:convert';
import 'dart:io';

import 'news_attachment.dart';
import 'radar_attachment.dart';

class MessageData {
  int id;
  final String? text;
  final String? audio;
  final bool writedByAdmin;
  final bool readed;
  final String createdAt;
  final NewsAttachment? news;
  final RadarAttachment? radar;
  final File? audioFile;
  final int? audioDuration;
  final int? duration;
  final String? writerName;
  final String? writerPhoto;

  MessageData({
    required this.id,
    required this.writedByAdmin,
    required this.readed,
    required this.createdAt,
    this.text,
    this.audio,
    this.news,
    this.radar,
    this.audioFile,
    this.audioDuration,
    this.duration,
    this.writerName,
    this.writerPhoto,
  });

  factory MessageData.fromJson(Map<String, dynamic> json) => MessageData(
        id: json['id'],
        text: json['text'],
        audio: json['audio'],
        writedByAdmin: json['writedByAdmin'],
        readed: json['readed'],
        createdAt: json['createdAt'],
        duration: json['duration'],
        writerName: json['writer']?['name'] ?? json['writerName'],
        writerPhoto: json['writer']?['photo'] ?? json['writerPhoto'],
        audioDuration: json['waveform'] == null
            ? null
            : jsonDecode(json['waveform'])['duration'] ?? 0,
        radar: json['radar'] == null
            ? null
            : RadarAttachment.fromJson(json['radar']),
        news:
            json['news'] == null ? null : NewsAttachment.fromJson(json['news']),
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'text': text,
        'audio': audio,
        'writedByAdmin': writedByAdmin,
        'readed': readed,
        'createdAt': createdAt,
        'duration': duration,
        'writerName': writerName,
        'writerPhoto': writerPhoto,
        'news': news?.toJson(),
        'radar': radar?.toJson(),
      };

  MessageData copyWith({
    int? id,
    String? text,
    String? audio,
    bool? writedByAdmin,
    bool? readed,
    String? createdAt,
    NewsAttachment? news,
    RadarAttachment? radar,
    File? audioFile,
    int? audioDuration,
    int? duration,
    String? writerName,
    String? writerPhoto,
  }) {
    return MessageData(
      id: id ?? this.id,
      text: text ?? this.text,
      audio: audio ?? this.audio,
      writedByAdmin: writedByAdmin ?? this.writedByAdmin,
      readed: readed ?? this.readed,
      news: news ?? this.news,
      radar: radar ?? this.radar,
      createdAt: createdAt ?? this.createdAt,
      audioFile: audioFile ?? this.audioFile,
      audioDuration: audioDuration ?? this.audioDuration,
      duration: duration ?? this.duration,
      writerName: writerName ?? this.writerName,
      writerPhoto: writerPhoto ?? this.writerPhoto,
    );
  }
}
