package com.sptg.iot.biz.listener;

import com.sptg.iot.biz.controller.IotAuthController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    //视频云登录token缓存名字
    public static final String IOT_AUTH_ACCESS_TOKEN = "sptg:iot:auth:accessToken";
    private final IotAuthController iotAuthController;

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     * @param iotAuthController
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, IotAuthController iotAuthController) {
        super(listenerContainer);
        this.iotAuthController = iotAuthController;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String keyStr = message.toString();
        if(keyStr.startsWith(IOT_AUTH_ACCESS_TOKEN)) {
            String appId = keyStr.split("@#")[1];
            this.iotAuthController.auth(appId);
        }
    }
}
