package com.bonus.file.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FileDownloadUtils {

    public static boolean downloadFile(String urlStr, String destination) throws IOException {
        if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
            return downloadHttpFile(urlStr, destination);
        } else if (urlStr.startsWith("ftp://")) {
            return downloadFtpFile(urlStr, destination);
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + urlStr);
        }
    }

    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;
    }

//    public static String replaceUrlPrefix(String originalUrl, String newPrefix) {
//        // 使用正则表达式匹配 URL 中的 "statics" 及其之前的部分
//        String regex = "^(.*?/statics)";
//        return originalUrl.replaceFirst(regex, newPrefix);
//    }

//    public static void main(String[] args) {
//        try {
//            // 示例下载文件
//            String httpUrl = "http://example.com/file.txt";
//            String ftpUrl = "ftp://username:password@ftp.example.com/file.txt";
//            String destination = "downloaded_file.txt";
//
//            // 下载HTTP文件
//            downloadFile(httpUrl, destination);
//
//            // 下载FTP文件
//            downloadFile(ftpUrl, destination);
//
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//    }
}
