package com.sptg.video.cloud.biz.listener;

import com.sptg.video.cloud.api.entity.VCAccount;
import com.sptg.video.cloud.biz.controller.VCAccountController;
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缓存名字
    private final static String VIDEO_CLOUD_LOGIN_TOKEN = "video:cloud:login:token";
    private final VCAccountController vcAccountController;

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String keyStr = message.toString();
        if(keyStr.startsWith(VIDEO_CLOUD_LOGIN_TOKEN)) {
            String accountName = keyStr.split("-")[1];
            VCAccount account = new VCAccount();
            account.setAccountName(accountName);
            this.vcAccountController.login(account);
        }
    }
}
