package com.xinda.bootstrap.tcp.config;

import com.xinda.base.session.Session;
import com.xinda.base.session.SessionListener;
import com.xinda.common.core.mq.DeviceStatusBo;
import com.xinda.common.enums.DeviceStatus;
import com.xinda.mq.redischannel.consumer.DeviceStatusConsumer;

import com.xinda.base.util.DeviceUtils;
import com.xinda.mqtt.manager.MqttRemoteManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author bill
 */
@Slf4j
@Service
public class TcpSessionListener implements SessionListener {

    @Resource
    private MqttRemoteManager remoteManager;
    @Resource
    private DeviceStatusConsumer statusConsumer;

    /** 客户端建立连接 */
    @Override
    public void sessionCreated(Session session) {

    }

    /** 客户端完成注册或鉴权 */
    @Override
    public void sessionRegistered(Session session) {
        DeviceStatusBo statusBo = DeviceUtils.buildStatusMsg(session.getChannel(), session.getClientId(),
                DeviceStatus.ONLINE, session.getIp());
        statusConsumer.consume(statusBo);
        remoteManager.pushDeviceStatus(-1L,statusBo.getSerialNumber(),statusBo.getStatus());
        log.info("TCP客户端:[{}],注册上线",session.getClientId());
    }

    /** 客户端注销或离线 */
    @Override
    public void sessionDestroyed(Session session) {
        /*推送离线消息到mq处理*/
        DeviceStatusBo statusBo = DeviceUtils.buildStatusMsg(session.getChannel(),
                session.getClientId(), DeviceStatus.OFFLINE, session.getIp());
        statusConsumer.consume(statusBo);
        remoteManager.pushDeviceStatus(-1L,statusBo.getSerialNumber(),statusBo.getStatus());
        log.info("TCP客户端:[{}],离线",session.getClientId());

    }
}
