package com.ffii.towngas.config;

import javax.annotation.PostConstruct;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConsumerConfig {
  @Value("${spring.mqtt.username}")
  private String username;

  @Value("${spring.mqtt.password}")
  private String password;

  @Value("${spring.mqtt.url}")
  private String hostUrl;

  @Value("${spring.mqtt.client.id}")
  private String clientId;

  @Value("${spring.mqtt.default.topic}")
  private String defaultTopic;

  private MqttClient client;

  @PostConstruct
  public void init() {
    connect();
  }

  public void connect() {
    try {
      // Create a client instance
      client = new MqttClient(hostUrl, clientId, new MemoryPersistence());
      // Create a connection option object
      MqttConnectOptions options = new MqttConnectOptions();
      // set connection option
      options.setCleanSession(true);
      options.setUserName(username);
      options.setPassword(password.toCharArray());
      options.setConnectionTimeout(100);
      options.setKeepAliveInterval(20);
      options.setWill("willTopic", (clientId + "Disconnected").getBytes(), 0, false);
      client.setCallback(new MqttConsumerCallBack());
      System.out.println("Start Connection");
      client.connect(options);
      System.out.println("End Connection");
      int[] qos = { 1, 1 };
      // Topics
      String[] topics = { "topic1", "topic2" };
      client.subscribe(topics, qos);
    } catch (MqttException e) {
      e.printStackTrace();
    }
  }

  public void disConnect() {
    try {
      client.disconnect();
    } catch (MqttException e) {
      e.printStackTrace();
    }
  }

  public void subscribe(String topic, int qos) {
    try {
      client.subscribe(topic, qos);
    } catch (MqttException e) {
      e.printStackTrace();
    }
  }
}