// PowerClampModel class to represent the response
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';

class PowerClampModel {
  String productUuid;
  String productType;
  PowerStatus status;

  PowerClampModel({
    required this.productUuid,
    required this.productType,
    required this.status,
  });

  factory PowerClampModel.fromJson(Map<String, dynamic> json) {
    return PowerClampModel(
      productUuid: json['productUuid'] as String? ?? '',
      productType: json['productType'] as String? ?? '',
      status: PowerStatus.fromJson(json['status'] as Map<String, dynamic>? ?? {}),
    );
  }

  PowerClampModel copyWith({
    String? productUuid,
    String? productType,
    PowerStatus? statusPower,
  }) {
    return PowerClampModel(
      productUuid: productUuid ?? this.productUuid,
      productType: productType ?? this.productType,
      status: statusPower ?? status,
    );
  }
}

class PowerStatus {
  Phase phaseA;
  Phase phaseB;
  Phase phaseC;
  Phase general;

  PowerStatus({
    required this.phaseA,
    required this.phaseB,
    required this.phaseC,
    required this.general,
  });

  factory PowerStatus.fromJson(Map<String, dynamic> json) {
    return PowerStatus(
      phaseA: Phase.fromJson(json['phaseA'] as List<dynamic>? ?? []),
      phaseB: Phase.fromJson(json['phaseB'] as List<dynamic>? ?? []),
      phaseC: Phase.fromJson(json['phaseC'] as List<dynamic>? ?? []),
      general: Phase.fromJson(json['general'] as List<dynamic>? ?? []),
    );
  }

  factory PowerStatus.fromStatusList(List<Status> statuses) {
    List<DataPoint> extractPhase(String prefix) {
      return statuses
          .where((s) => s.code.endsWith(prefix))
          .map((s) => DataPoint(code: s.code, value: s.value))
          .toList();
    }

    return PowerStatus(
      phaseA: Phase(dataPoints: extractPhase('A')),
      phaseB: Phase(dataPoints: extractPhase('B')),
      phaseC: Phase(dataPoints: extractPhase('C')),
      general: Phase(dataPoints: extractPhase('')),
    );
  }
}

class Phase {
  List<DataPoint> dataPoints;

  Phase({required this.dataPoints});

  factory Phase.fromJson(List<dynamic> json) {
    return Phase(
      dataPoints: json.map((x) => DataPoint.fromJson(x)).toList(),
    );
  }
}

class DataPoint {
  final String? code;
  final String? customName;
  final int? dpId;
  final int? time;
  final String? type;
  final dynamic value;

  DataPoint({
    this.code,
    this.customName,
    this.dpId,
    this.time,
    this.type,
    this.value,
  });

  factory DataPoint.fromJson(Map<String, dynamic> json) {
    return DataPoint(
      code: json['code'] as String?,
      customName: json['customName'] as String?,
      dpId: json['dpId'] as int?,
      time: json['time'] as int?,
      type: json['type'] as String?,
      value: json['value'] as dynamic,
    );
  }
}
