package com.bcxin.backend.domain.utils.ftp;

import com.bcxin.backend.domain.configs.FileModeConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * <b>  </b>
 * @author ZXF
 * @create 2023/07/07 0007 13:47
 * @version
 * @注意事项 </b>
 */
@Slf4j
public class FtpFactory {
    private static final Logger logger = LoggerFactory.getLogger(FtpFactory.class);


    //有界队列
    private static final ArrayBlockingQueue<FtpConnection> arrayBlockingQueue = new ArrayBlockingQueue<>(FileModeConfig.ftpConnectionSize);


    protected FtpFactory(){
        log.info("init ftpConnectionSize "+FileModeConfig.ftpConnectionSize);
        for(int i = 0; i< FileModeConfig.ftpConnectionSize; i++){
            //表示如果可能的话，将 e 加到 BlockingQueue 里，即如果 BlockingQueue 可以容纳，则返回 true，否则返回 false
            arrayBlockingQueue.offer(new FtpConnection());
        }
    }

    /**
     * 获取连接
     *
     * @return
     */

    public FtpConnection getFtp() {
        FtpConnection poll = null;
        try {
            //取走 BlockingQueue 里排在首位的对象，若 BlockingQueue 为空，阻断进入等待状态直到 Blocking 有新的对象被加入为止
            poll = arrayBlockingQueue.take();
        } catch (InterruptedException e) {
            logger.error("获取FTP连接发生异常", e);
        }

        return poll;
    }

    /**
     * 释放连接
     * @param ftp
     * @return
     */
    public boolean relase(FtpConnection ftp){
        return arrayBlockingQueue.offer(ftp);
    }

    /**
     * 删除连接
     *
     * @param ftp
     */

    public void remove(FtpConnection ftp) {
        arrayBlockingQueue.remove(ftp);
    }

    /**
     * 关闭连接
     */
    public void close() {
        for (FtpConnection connection : arrayBlockingQueue) {
            try {
                connection.disconnect();
            } catch (IOException e) {
                logger.error("关闭FTP连接发生异常", e);
            }
        }
    }
}
