/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hw.mqtt.listener;

import com.alibaba.fastjson2.JSONArray;
import com.hw.mqtt.enums.ConnectStatus;
import com.hw.mqtt.enums.DeviceType;
import com.hw.mqtt.enums.RedisKeys;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import net.dreamlu.iot.mqtt.core.server.event.IMqttConnectStatusListener;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 状态监听器
 * 性能损失小
 * @author WenJY
 * @date 2023-03-14 12:17
 * @param null 
 * @return null
 */
@Service
public class MqttConnectStatusListener implements IMqttConnectStatusListener, SmartInitializingSingleton, DisposableBean {
	private static final Logger logger = LoggerFactory.getLogger(MqttConnectStatusListener.class);

	private final ApplicationContext context;
	private final StringRedisTemplate redisTemplate;
	private MqttServerCreator serverCreator;
	private MqttServerTemplate mqttServerTemplate;

	@Value("${broker.connectStatus.enable}")
	private boolean publishConnectStatusEnable;

	@Value("${broker.connectStatus.topic}")
	private String publishConnectStatusTopic;

	public MqttConnectStatusListener(ApplicationContext context, StringRedisTemplate redisTemplate) {
		this.context = context;
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void online(ChannelContext context, String clientId, String username) {
		logger.info("Mqtt clientId:{} username:{} online.", clientId, username);
		redisTemplate.opsForSet().add(getRedisKey(), clientId);
		pushConnectStatus(clientId,ConnectStatus.connct);
	}

	@Override
	public void offline(ChannelContext context, String clientId, String username, String reason) {
		logger.info("Mqtt clientId:{} username:{} offline reason:{}.", clientId, username, reason);
		redisTemplate.opsForSet().remove(getRedisKey(), clientId);
		pushConnectStatus(clientId,ConnectStatus.disconnect);
	}

	/**
	 * 设备上下线存储，key 的值为 前缀:nodeName
	 *
	 * @return redis key
	 */
	private String getRedisKey() {
		return RedisKeys.CONNECT_STATUS.getKey(serverCreator.getNodeName());
	}

	@Override
	public void afterSingletonsInstantiated() {
		this.serverCreator = context.getBean(MqttServerCreator.class);
		this.mqttServerTemplate = context.getBean(MqttServerTemplate.class);
	}

	@Override
	public void destroy() throws Exception {
		// 停机时删除集合
		redisTemplate.opsForSet().remove(getRedisKey());
	}

	/**
	 * 推送设备状态到指定主题
	 * @param clientId
	 * @param connectStatus
	 */
	public void pushConnectStatus(String clientId, ConnectStatus connectStatus){
		if(publishConnectStatusEnable){
			Map<String,Object> entityMap = new HashMap<>();
			entityMap.put("msg","设备设备连接状态信息");
			entityMap.put("deviceType", DeviceType.edge.getKey());
			entityMap.put("deviceCode",clientId);
			entityMap.put("connectStatus",connectStatus.getKey());
			entityMap.put("statusTime",System.currentTimeMillis());
			String jsonString = JSONArray.toJSONString(entityMap);
			boolean result = mqttServerTemplate.publishAll(publishConnectStatusTopic, jsonString.getBytes(StandardCharsets.UTF_8));
			if(result){
				logger.info("客户端："+clientId+"；"+ (connectStatus == ConnectStatus.connct ? "连接" :"断开") +"状态推送成功");
			}else {
				logger.info("客户端："+clientId+"；"+ (connectStatus == ConnectStatus.connct ? "连接" :"断开") +"状态推送失败");
			}
		}else {
			logger.info("未开启设备连接状态推送");
		}

	}
}
