import mqtt from 'mqtt';

function uint8array2json(uint8array) {
  if (!uint8array || !uint8array.length) {
    return uint8array;
  }
  let decoder = new TextDecoder("utf-8");
  let content = decoder.decode(uint8array);
  return content ? JSON.parse(content) : content;
}

export default {
  namespaced: true,
  state: {
    client: null, //mqtt client
    clientId: "",
    url: "", //mqtt地址
    dataSet: {
      //数据集
      /* deviceHardId: {
        type(如258): {}
      } */
    },
  },
  mutations: {
    setClient(state, data) {
      state.client = data;
    },
    setClientId(state, data) {
      state.clientId = data;
    },
    setUrl(state, data) {
      state.url = data;
    },
    setDataSet(state, data) {
      state.dataSet = data;
    },
  },
  actions: {
    init({ commit, state }, data) {
      let protocol = state.url.replace(/(.+)\:\/\/.*/, "$1");
      let clientId = Date.now();
      let client = mqtt.connect(data.url, {
        protocol,
        clientId,
      });
      
      commit("setClient", client);
      commit("setClientId", clientId);

      client.on("reconnect", function (reconnect) {
        console.log(reconnect, "reconnect");
      });

      client.on("message", (topic, payload, packet) => {
        let data = uint8array2json(payload);
        let deviceHardId = packet.topic.split("/")[2];

        if (!state.dataSet[deviceHardId]) {
          state.dataSet[deviceHardId] = {};
        }
        state.dataSet[deviceHardId][data.type] = data;
        let temp = {};
        Object.keys(state.dataSet).forEach((key) => {
          temp[key] = state.dataSet[key];
        });
        commit("setDataSet", temp);
      });

      /**
       * 订阅无人机上线下线消息
       */
      /* subscribe(`on_and_off_broker`, (e) => {
        console.log("subscribe on_and_off_broker");
      }); */

      return new Promise((resolve, reject) => {
        client.on("connect", () => {
          console.log("mqtt is connected");
          resolve();
        });

        client.on("`error`", (error) => {
          console.log("mqtt is `error`", error);
          reject();
        });
      });
    },
    /**
     * 订阅
     * @param {*} topic
     * @param {*} callback
     */
    subscribe({ state }, { topic, callback }) {
      if (!topic) {
        return topic;
      }
      let { client } = state;
      if (client) {
        console.log("订阅数据a", topic);
        client.subscribe(topic, callback);
      }
    },
    /**
     * 取消订阅
     * @param {*} topic
     * @returns
     */
    unsubscribe({ state }, { topic }) {
      if (!topic) {
        return topic;
      }
      let { client } = state;
      if (client) {
        client.unsubscribe(topic);
      }
    },
  },
};