package com.bcxin.signature.util.ftp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadFtpContext {
    private static final Logger logger = LoggerFactory.getLogger(ThreadFtpContext.class);
    private final static ThreadLocal<FtpConnection> ftpConnection = new ThreadLocal<FtpConnection>() {
        @Override
        protected FtpConnection initialValue() {
            return new FtpConnection();
        }

        @Override
        public FtpConnection get() {
            FtpConnection connection = super.get();
            if (connection == null || !connection.isConnected()) {
                connection = new FtpConnection();

                super.set(connection);
            }

            return connection;
        }
    };

    private final static ThreadLocal<FtpWriteConnection> ftpWriteConnection = new ThreadLocal<FtpWriteConnection>() {
        @Override
        protected FtpWriteConnection initialValue() {
            return new FtpWriteConnection();
        }

        @Override
        public FtpWriteConnection get() {
            FtpWriteConnection connection = super.get();
            if (connection == null || !connection.isConnected()) {
                connection = new FtpWriteConnection();

                super.set(connection);
            }

            return connection;
        }
    };

    public static FtpConnection getFtpConnection() {
        return ftpConnection.get();
    }

    public static FtpWriteConnection getFtpWriteConnection() {
        return ftpWriteConnection.get();
    }

    public static void disConnectFtpWriter() {
        try {
            FtpWriteConnection connection = ftpWriteConnection.get();
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            logger.error("failed to ftpWriteConnection ftp", ex);
        }
    }

    public static void disConnectFtp() {
        try {
            FtpConnection connection = ftpConnection.get();
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            logger.error("failed to ftpConnection ftp", ex);
        }
    }
}
