package com.yeejoin.amos.api.openapi.listener;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.OpenapiApplication;
import com.yeejoin.amos.api.openapi.listener.event.FileToBeDeleteEvent;
import com.yeejoin.amos.api.openapi.service.StartPlatformTokenService;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class FileToBeDeleteEventListener implements ApplicationListener<FileToBeDeleteEvent> {

    private static final Logger logger = LogManager.getLogger(FileToBeDeleteEventListener.class);

    @Value("${file.delete.thread.number:3}")
    private int threadNumber;

    private final BlockingQueue<List<String>> blockingQueue = new LinkedBlockingQueue<>();

    private ExecutorService executorService;

    @Autowired
    StartPlatformTokenService startPlatformTokenService;

    @Override
    public void onApplicationEvent(FileToBeDeleteEvent event) {
        log.info("收到资源文件删除消息:{}", JSONObject.toJSONString(event.getFileUrlList()));
        blockingQueue.add(event.getFileUrlList());
    }

    @PostConstruct
    public void init() {
        executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        startPlatformTokenService.getToken();
                        List<String> fileList = blockingQueue.take();
                        logger.info("删除文件开始:{}", JSONObject.toJSONString(fileList));
                        Systemctl.fileStorageClient.deleteFile(fileList.toArray(new String[0]));
                        log.info("删除文件完成");
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });
        }
    }

    @PreDestroy
    public void shutdown() {
        if (executorService != null) {
            log.info("开始关闭executorService:{}", executorService);
            executorService.shutdown();
        }
    }
}
