import 'package:freezed_annotation/freezed_annotation.dart';

part 'icon_library.freezed.dart';
part 'icon_library.g.dart';

@freezed
abstract class IconEntry with _$IconEntry {
  const factory IconEntry({
    @JsonKey(fromJson: _stringOrEmpty) @Default('') String name,
    @JsonKey(fromJson: _stringOrEmpty) @Default('') String url,
  }) = _IconEntry;

  factory IconEntry.fromJson(Map<String, dynamic> json) =>
      _$IconEntryFromJson(json);
}

@freezed
abstract class IconLibrary with _$IconLibrary {
  const factory IconLibrary({

    required String sourceUrl,
    @JsonKey(fromJson: _stringOrEmpty) @Default('') String name,
    @JsonKey(fromJson: _stringOrEmpty) @Default('') String description,
    @Default(<IconEntry>[]) List<IconEntry> icons,
  }) = _IconLibrary;

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


  static IconLibrary parse(String sourceUrl, Map<String, dynamic> json) {
    final raw = json['icons'];
    final iconsList = raw is List
        ? raw
              .whereType<Map<String, dynamic>>()
              .map(IconEntry.fromJson)
              .where((e) => e.url.isNotEmpty)
              .toList()
        : const <IconEntry>[];
    return IconLibrary(
      sourceUrl: sourceUrl,
      name: (json['name'] as String?) ?? '',
      description: (json['description'] as String?) ?? '',
      icons: iconsList,
    );
  }
}

String _stringOrEmpty(Object? value) => value?.toString() ?? '';
