package com.bcxin.signature.util.ftp;

import com.bcxin.signature.config.FileModeConfig;
import com.bcxin.signature.config.FileWriteConfig;
import lombok.extern.slf4j.Slf4j;

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 FtpWriteFactory {


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


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

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

    public FtpWriteConnection getFtp() {
        FtpWriteConnection poll = null;
        try {
            //取走 BlockingQueue 里排在首位的对象，若 BlockingQueue 为空，阻断进入等待状态直到 Blocking 有新的对象被加入为止
            poll = arrayBlockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return poll;
    }

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

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

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

    /**
     * 关闭连接
     */
    public void close() {
        for (FtpWriteConnection connection : arrayBlockingQueue) {
            try {
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
