package com.bonus.file.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.file.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;

/**
 * 。
 *
 * @author weiwei
 */
public class FileDownloadUtils {

    private final static String HTTP_START_STR = "http://";
    private final static String HTTPS_START_STR = "https://";
    private final static String FTP_START_STR = "ftp:/";

    public static boolean downloadFile(HttpServletResponse response,String urlStr) throws IOException {
        if (urlStr.startsWith(HTTP_START_STR) || urlStr.startsWith(HTTPS_START_STR)) {
            return downloadHttpFile(response, urlStr);
        } else if (urlStr.startsWith(FTP_START_STR)) {
            return downloadFtpFile(response, urlStr);
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + urlStr);
        }
    }

    private static boolean downloadHttpFile(HttpServletResponse response, String urlStr) throws IOException {
        //处理中文文件名的问题
        String fileName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        String newPath = urlStr.substring(0, urlStr.lastIndexOf('/') + 1) + encodedFileName;

        URL urlNew = new URL(newPath);
        HttpURLConnection connection = (HttpURLConnection) urlNew.openConnection();
        connection.setRequestMethod("GET");

       com.bonus.file.utils.FileUtils.setResponseHeaderByUrl(response, urlStr);
        try  {
            int code = connection.getResponseCode();
            InputStream inputStream = connection.getInputStream();
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("HTTP download completed: ");
        } catch (Exception e) {
            throw new IOException("没有找到文件");
        }

        finally {
            connection.disconnect();
        }
        return true;
    }

    private static boolean downloadFtpFile(HttpServletResponse response, String urlStr) throws IOException{
        FTPClient ftpClient = new FTPClient();
        try {
            URL url = new URL(urlStr);
            String host = url.getHost();
            int port = url.getPort() == -1 ? 21 : url.getPort();
            String userInfo = url.getUserInfo();
            String[] credentials = userInfo != null ? userInfo.split(":") : new String[]{"anonymous", ""};
            String username = credentials[0];
            String password = credentials.length > 1 ? credentials[1] : "";

            //处理中文文件名的问题
            String urlPath = url.getPath();
            String path = urlPath.substring(urlStr.lastIndexOf('/') + 1);
            String encodedFileName = URLEncoder.encode(path, "UTF-8");

            String remoteFilePath = urlPath.substring(0, urlStr.lastIndexOf('/') + 1) + encodedFileName;;

            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            com.bonus.file.utils.FileUtils.setResponseHeaderByUrl(response, urlStr);

            try (InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
                 ServletOutputStream outputStream = response.getOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                if (ftpClient.completePendingCommand()) {
                    System.out.println("FTP download completed: ");
                } else {
                    System.out.println("Failed to complete FTP download: ");
                }
            }
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            ftpClient.logout();
            ftpClient.disconnect();
        }
        return true;
    }

//    private static boolean downloadHttpFile(String urlStr, String destination) throws IOException {
//        URL url = new URL(urlStr);
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        connection.setRequestMethod("GET");
//
//        try (InputStream inputStream = connection.getInputStream();
//             FileOutputStream outputStream = new FileOutputStream(destination)) {
//
//            byte[] buffer = new byte[4096];
//            int bytesRead = -1;
//            while ((bytesRead = inputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, bytesRead);
//            }
//            System.out.println("HTTP download completed: " + destination);
//        } finally {
//            connection.disconnect();
//        }
//        return true;
//    }
//
//    private static boolean downloadFtpFile(String urlStr, String destination) throws IOException {
//        FTPClient ftpClient = new FTPClient();
//        try {
//            URL url = new URL(urlStr);
//            String host = url.getHost();
//            int port = url.getPort() == -1 ? 21 : url.getPort();
//            String userInfo = url.getUserInfo();
//            String[] credentials = userInfo != null ? userInfo.split(":") : new String[]{"anonymous", ""};
//            String username = credentials[0];
//            String password = credentials.length > 1 ? credentials[1] : "";
//            String remoteFilePath = url.getPath();
//
//            ftpClient.connect(host, port);
//            ftpClient.login(username, password);
//            ftpClient.enterLocalPassiveMode();
//            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//
//            try (InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
//                 FileOutputStream outputStream = new FileOutputStream(destination)) {
//
//                byte[] buffer = new byte[4096];
//                int bytesRead = -1;
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//
//                if (ftpClient.completePendingCommand()) {
//                    System.out.println("FTP download completed: " + destination);
//                } else {
//                    System.out.println("Failed to complete FTP download: " + destination);
//                }
//            }
//        } finally {
//            ftpClient.logout();
//            ftpClient.disconnect();
//        }
//        return true;
//    }
}
