// lib/models/category.dart

class NewCategory {
  final int id;
  final String categoryName;
  final int categoryNumber;
  final Duration duration;
  final int numOfMember;
  final bool family;
  final bool female;
  final String? time;

  NewCategory({
    required this.id,
    required this.categoryName,
    this.time,
    required this.categoryNumber,
    required this.duration,
    required this.numOfMember,
    required this.family,
    required this.female,
  });

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is NewCategory &&
              runtimeType == other.runtimeType &&
              id == other.id;

  @override
  int get hashCode => id.hashCode;

  factory NewCategory.fromJson(Map<String, dynamic> json) {
    final fullCategoryName = json['category_name'] as String;
    final parts = fullCategoryName.split('-');
    final baseName = parts[0].trim();
    final time = parts.length > 1 ? parts[1].trim() : null;

    return NewCategory(
      id: json['id'] ?? 0,
      categoryName: json['category_name'] ?? 'Unknown Category',
      time: time,
      categoryNumber: json['category_number'] ?? 0,
      duration: parseDuration(json['duration']),
      numOfMember: json['num_of_member'] ?? 1,
      family: json['family'] ?? false,
      female: json['female'] ?? false,
    );
  }

  String get baseCategory => categoryName.split('-')[0].trim();

  static Duration parseDuration(String s) {
    int hours = 0;
    int minutes = 0;
    int micros;
    List<String> parts = s.split(':');
    if (parts.length > 2) {
      hours = int.parse(parts[parts.length - 3]);
    }
    if (parts.length > 1) {
      minutes = int.parse(parts[parts.length - 2]);
    }
    micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
    return Duration(hours: hours, minutes: minutes, microseconds: micros);
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'category_name': categoryName,
      'category_number': categoryNumber,
      'duration': duration.inSeconds,
      'num_of_member': numOfMember,
      'family': family,
      'female': female,
    };
  }
}