import 'SetLog.dart';

class SessionLog {
  String? id;

  String templateId;

  String templateName;

  DateTime? startedAt;

  DateTime? endedAt;

  /// Session RPE 1..10.
  double sessionRpe;

  /// Readiness check-in at session start.
  int sleepScore;

  int sorenessScore;

  int motivationScore;

  /// Did you do the session, or a watered-down version of it?
  double integrityScore;

  bool duringDeload;

  List<SetLog> sets;

  SessionLog({
    this.id,
    this.templateId = "",
    this.templateName = "",
    this.startedAt,
    this.endedAt,
    this.sessionRpe = 0,
    this.sleepScore = 0,
    this.sorenessScore = 0,
    this.motivationScore = 0,
    this.integrityScore = 0,
    this.duringDeload = false,
    List<SetLog>? sets,
  }) : sets = sets ?? <SetLog>[];

  factory SessionLog.fromJson(Map<String, dynamic> json) {
    return SessionLog(
      id: json['id'],
      templateId: json['templateId'] ?? "",
      templateName: json['templateName'] ?? "",
      startedAt: DateTime.tryParse(json['startedAt'] ?? ""),
      endedAt: DateTime.tryParse(json['endedAt'] ?? ""),
      sessionRpe: (json['sessionRpe'] ?? 0).toDouble(),
      sleepScore: json['sleepScore'] ?? 0,
      sorenessScore: json['sorenessScore'] ?? 0,
      motivationScore: json['motivationScore'] ?? 0,
      integrityScore: (json['integrityScore'] ?? 0).toDouble(),
      duringDeload: json['duringDeload'] ?? false,
      sets: json['sets'] == null
          ? <SetLog>[]
          : (json['sets'] as List).map((item) => SetLog.fromJson(item)).toList(),
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['templateId'] = templateId;
    data['templateName'] = templateName;
    data['startedAt'] = startedAt?.toIso8601String();
    data['endedAt'] = endedAt?.toIso8601String();
    data['sessionRpe'] = sessionRpe;
    data['sleepScore'] = sleepScore;
    data['sorenessScore'] = sorenessScore;
    data['motivationScore'] = motivationScore;
    data['integrityScore'] = integrityScore;
    data['duringDeload'] = duringDeload;
    data['sets'] = sets.map((item) => item.toJson()).toList();
    return data;
  }

  int get durationMinutes {
    if (startedAt == null || endedAt == null) {
      return 0;
    }
    return endedAt!.difference(startedAt!).inMinutes;
  }

  /// Weekly tonnage contribution for loaded work.
  double get tonnage {
    double total = 0;
    for (SetLog entry in sets) {
      total = total + (entry.loadKg * entry.reps);
    }
    return total;
  }

  int get contacts {
    int total = 0;
    for (SetLog entry in sets) {
      total = total + entry.contacts;
    }
    return total;
  }
}
