import 'dart:convert';

class BleDevice {
  const BleDevice({
    required this.name,
    required this.id,
    required this.rssi,
  });

  final String name;
  final String id;
  final int rssi;
}

class BleStatus {
  const BleStatus({
    required this.ok,
    required this.action,
    this.state,
    this.error,
  });

  factory BleStatus.fromJson(Map<String, dynamic> json) {
    return BleStatus(
      ok: json['ok'] == true,
      action: (json['action'] ?? '').toString(),
      state: json['state']?.toString(),
      error: json['error']?.toString(),
    );
  }

  factory BleStatus.fromRawJson(String source) {
    final dynamic decoded = jsonDecode(source);
    if (decoded is! Map<String, dynamic>) {
      throw const FormatException('BLE status payload is not a JSON object');
    }
    return BleStatus.fromJson(decoded);
  }

  static const BleStatus idle = BleStatus(ok: true, action: 'idle');

  final bool ok;
  final String action;
  final String? state;
  final String? error;

  bool get isQueued => state == 'queued';

  bool get isSuccess => ok && !isQueued;

  String get message {
    if ((error ?? '').isNotEmpty) {
      return error!;
    }
    if ((state ?? '').isNotEmpty) {
      return state!;
    }
    return action;
  }
}

enum ProvisioningState {
  scanning,
  connecting,
  writingCredentials,
  connectingWifi,
  success,
  failed,
}
