import 'dart:convert';
import 'dart:ui';

import 'package:json_annotation/json_annotation.dart';

import '../global/utils.dart';

part 'shared_note.g.dart';

@JsonSerializable()
class SharedNote {
  SharedNote({
    this.id,
    required this.familyId,
    required this.createdByUserId,
    required this.content,
    required this.title,
    this.color,
    this.createdAt,
    this.updatedAt,
    required this.tagIds,
    this.isMarkdown = false,
    this.hide = false,
  });

  final int? id;
  final int familyId, createdByUserId;
  String content, title;

  @JsonKey(fromJson: _tagIdsFromJson, toJson: _tagIdsToJson)
  List<int> tagIds;

  @JsonKey(fromJson: optionalColorFromJson, toJson: optionalColorToJson)
  Color? color;

  @JsonKey(fromJson: boolFromJson, toJson: boolToJson)
  bool isMarkdown;

  @JsonKey(fromJson: boolFromJson, toJson: boolToJson)
  final bool hide;

  @JsonKey(fromJson: dateFromJson, toJson: dateToJson)
  final DateTime? createdAt;

  @JsonKey(fromJson: dateFromJson, toJson: dateToJson)
  final DateTime? updatedAt;

  factory SharedNote.fromJson(Map<String, dynamic> json) =>
      _$SharedNoteFromJson(json);

  Map<String, dynamic> toJson() => _$SharedNoteToJson(this);

  factory SharedNote.copy(SharedNote note) =>
      SharedNote.fromJson(note.toJson());
}

List<int> _tagIdsFromJson(String tagJson) {
  final tagsMap = jsonDecode(tagJson) as List<dynamic>;
  return tagsMap
      .map(
        (e) => int.parse(e),
      )
      .toList();
}

String _tagIdsToJson(List<int> tagIds) {
  return jsonEncode(tagIds);
}
