package com.skr.mdm.observer;

import cn.hutool.json.JSONUtil;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.skr.mdm.bean.dto.BrowserWebsocketDTO;
import com.skr.mdm.enums.BrowserWebsocketType;
import com.skr.mdm.event.FileUploadProgressEvent;
import com.skr.mdm.util.RedisGetKeyUtil;
import com.skr.mdm.util.RedisUtils;
import com.skr.mdm.websocket.WebsocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

/**
 * @author nfq
 * @date 2023/11/30 17:05:36
 */
@Component
@Slf4j
public class FileUploadProgressObserver {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private EventBus eventBus;

    @PostConstruct
    public void register() {
        eventBus.register(this);
    }

    @Subscribe
    public void onApplicationEvent(FileUploadProgressEvent event) {
        if (redisUtils.get(RedisGetKeyUtil.getFileUploadProgressKey(event.getFileId())) != null) {
            String adminSession  = redisUtils.get(RedisGetKeyUtil.getFileUploadProgressKey(event.getFileId())).toString();
            log.info("文件上传进度监听：{} adminSession:{}", JSONUtil.toJsonStr(event), adminSession);
            BrowserWebsocketDTO websocketDTO = BrowserWebsocketDTO.builder()
                    .wsType(BrowserWebsocketType.FILE_PROGRESS.getWsType())
                    .data(new BigDecimal(event.getProcess()))
                    .build();
            WebsocketServer.sendAdminMessage(adminSession, JSONUtil.toJsonStr(websocketDTO));
        }
    }
}
