import 'package:firebase_database/firebase_database.dart';
import '../models/sensor_data.dart';

class SensorService {
  final DatabaseReference _database = FirebaseDatabase.instance.ref();

  // Stream untuk mendapatkan data sensor secara real-time
  Stream<List<SensorData>> getSensorDataStream() {
    // Membuat broadcast stream yang bisa didengarkan oleh banyak listener
    return _database.child('sensor').onValue
      .asBroadcastStream()
      .map((event) {
        print('Raw Firebase Data: ${event.snapshot.value}'); // Debug print
        
        if (event.snapshot.value == null) {
          print('Firebase returned null data, using default values');
          // Mengembalikan nilai default jika tidak ada data
          return [
            SensorData(
              name: 'Suhu',
              value: 0.0,
              timestamp: DateTime.now(),
            ),
            SensorData(
              name: 'Kelembapan',
              value: 0.0,
              timestamp: DateTime.now(),
            ),
          ];
        }

        try {
          final data = Map<String, dynamic>.from(event.snapshot.value as Map);
          print('Parsed Data: $data'); // Debug print
          
          double tempValue = double.tryParse(data['temperature']?.toString() ?? '0.0') ?? 0.0;
          double humidValue = double.tryParse(data['Humidity']?.toString() ?? '0.0') ?? 0.0;
          
          print('Parsed Temperature: $tempValue, Humidity: $humidValue');
          
          return [
            SensorData(
              name: 'Suhu',
              value: tempValue,
              timestamp: DateTime.now(),
            ),
            SensorData(
              name: 'Kelembapan',
              value: humidValue,
              timestamp: DateTime.now(),
            ),
          ];
        } catch (e) {
          print('Error parsing data: $e');
          print('Original data was: ${event.snapshot.value}');
          
          // Mengembalikan nilai default jika parsing gagal
          return [
            SensorData(
              name: 'Suhu',
              value: 0.0,
              timestamp: DateTime.now(),
            ),
            SensorData(
              name: 'Kelembapan',
              value: 0.0,
              timestamp: DateTime.now(),
            ),
          ];
        }
      });
  }

  // Fungsi untuk menambah data sensor
  Future<void> addSensorData(SensorData sensorData) async {
    await _database.push().set({
      'name': sensorData.name,
      'value': sensorData.value,
      'timestamp': sensorData.timestamp.millisecondsSinceEpoch,
    });
  }

  // Fungsi untuk mengambil data sensor terakhir
  Future<SensorData?> getLatestSensorData(String sensorName) async {
    final DatabaseEvent event = await _database
        .orderByChild('name')
        .equalTo(sensorName)
        .limitToLast(1)
        .once();
    
    final Map<dynamic, dynamic>? values = 
        event.snapshot.value as Map?;
    
    if (values == null || values.isEmpty) return null;
    
    final value = values.values.first;
    return SensorData(
      name: value['name'],
      value: double.parse(value['value'].toString()),
      timestamp: DateTime.fromMillisecondsSinceEpoch(value['timestamp']),
    );
  }

  // Tambahkan stream untuk status relay
  Stream<Map<String, bool>> getRelayStatusStream() {
    return _database.child('relay').onValue
      .asBroadcastStream()
      .map((event) {
        print('Raw Relay Data: ${event.snapshot.value}');
        
        if (event.snapshot.value == null) return <String, bool>{};

        try {
          final data = Map<String, dynamic>.from(event.snapshot.value as Map);
          print('Parsed Relay Data: $data');
          
          return <String, bool>{
            'lamp': data['Lampu'] ?? false,
            'fan': data['Kipas'] ?? false,
          };
        } catch (e) {
          print('Error parsing relay data: $e');
          return <String, bool>{};
        }
      });
  }
} 