import 'dart:convert';

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

class MQTTService {
  static final MQTTService instance = MQTTService._();

  MQTTService._();

  late MqttServerClient client;

  Future connect() async {
    client = MqttServerClient(
      '192.168.1.27',
      'flutter_client',
    );

    client.port = 1883;

    client.keepAlivePeriod = 20;

    await client.connect();

    client.subscribe(
      'kopika/sensor',
      MqttQos.atLeastOnce,
    );
  }

  void sendControl(
    bool heater,
    bool fan,
  ) {
    final builder = MqttClientPayloadBuilder();

    builder.addString(
      jsonEncode({
        "heater": heater ? 1 : 0,
        "fan": fan ? 1 : 0,
      }),
    );

    client.publishMessage(
      "kopika/control",
      MqttQos.atLeastOnce,
      builder.payload!,
    );
  }
}
