import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class MQTTService {
  late MqttServerClient client;
  final String serverUri = 'broker.hivemq.com';
  final String topic = 'piCo/manualFeed';

  // Inisialisasi koneksi MQTT
  void initializeMQTT() {
    client = MqttServerClient.withPort(serverUri, 'flutter_client', 1883);
    client.logging(on: false);
    client.keepAlivePeriod = 20;
    client.onDisconnected = _onDisconnected;
    client.onConnected = _onConnected;
    client.onSubscribed = _onSubscribed;
    client.pongCallback = _pong;
  }

  // Callback saat koneksi ke server terputus
  void _onDisconnected() {
    print('Disconnected');
  }

  // Callback saat koneksi berhasil terhubung
  void _onConnected() {
    print('Connected');
  }

  // Callback saat berhasil subscribe ke topik
  void _onSubscribed(String topic) {
    print('Subscribed to topic $topic');
  }

  // Callback saat menerima pong dari broker
  void _pong() {
    print('Ping response client callback invoked');
  }

  // Method untuk menghubungkan ke broker MQTT
  Future<void> connect() async {
    try {
      await client.connect();
      print('Client connected');
      // Pindahkan sendManualFeedMessage ke luar try-catch agar bisa di await
    } catch (e) {
      print('Client exception - $e');
      client.disconnect();
      rethrow; // Tambahkan rethrow agar error bisa diteruskan
    }
  }

  // Method untuk mengirim pesan manual feed
  Future<void> sendManualFeedMessage() async {
    final builder = MqttClientPayloadBuilder();
    builder.addString('Makan');
    client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
    print('Message published');
  }

  // Method untuk menghentikan koneksi MQTT
  void disconnect() {
    client.disconnect();
    print('Client disconnected');
  }
}
