package utils

import (
	"fmt"
	"golang.org/x/net/proxy"
	"io"
	"net/http"
	"net/url"
	"os"
)

// DownloadFile 下载一个文件，调用http.Get()下载
func DownloadFile(downloadUrl, desFile string) (downloadOk bool, resultLog []string) {

	log.InfoF("Downloading file: %s", downloadUrl)
	resp, err := http.Get(downloadUrl)
	if err != nil {
		return false, []string{fmt.Sprintf("Error downloading file: %v", err)}
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return false, []string{fmt.Sprintf("Unexpected status code: %d", resp.StatusCode)}
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return false, []string{fmt.Sprintf("Error reading response body: %v", err)}
	}

	err = os.WriteFile(desFile, body, 0644)
	if err != nil {
		return false, []string{fmt.Sprintf("Error writing file to disk: %v", err)}
	}

	log.InfoF("Downloading complete: %s", downloadUrl)
	return true, []string{}
}

func DownloadFileBySocks5(downloadUrl string, socksProxyUrl string, proxyUser string, proxyPass string, desFile string) (downloadOk bool, resultLog []string) {
	// 解析下载URL
	_, err := url.Parse(downloadUrl)
	if err != nil {
		resultLog = append(resultLog, "Error parsing download URL: "+err.Error())
		return false, resultLog
	}

	// 创建文件
	out, err := os.Create(desFile)
	if err != nil {
		resultLog = append(resultLog, "Error creating file: "+err.Error())
		return false, resultLog
	}
	defer out.Close()

	// 创建HTTP客户端
	client := &http.Client{}

	// 如果提供了代理URL
	if socksProxyUrl != "" {
		// 解析代理URL
		parsedProxyUrl, err := url.Parse(socksProxyUrl)
		if err != nil {
			resultLog = append(resultLog, "Error parsing proxy URL: "+err.Error())
			return false, resultLog
		}

		// 使用SOCKS5代理
		auth := &proxy.Auth{User: proxyUser, Password: proxyPass}
		dialer, err := proxy.SOCKS5("tcp", parsedProxyUrl.Host, auth, proxy.Direct)
		if err != nil {
			resultLog = append(resultLog, "Error creating SOCKS5 dialer: "+err.Error())
			return false, resultLog
		}

		// 设置HTTP和HTTPS代理
		httpTransport := &http.Transport{
			Dial: dialer.Dial,
		}
		client.Transport = httpTransport
	}

	// 发送HTTP GET请求
	resp, err := client.Get(downloadUrl)
	if err != nil {
		resultLog = append(resultLog, "Error making GET request: "+err.Error())
		return false, resultLog
	}
	defer resp.Body.Close()

	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		resultLog = append(resultLog, "Server returned HTTP status "+resp.Status)
		return false, resultLog
	}

	// 将HTTP响应内容写入文件
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		resultLog = append(resultLog, "Error writing to file: "+err.Error())
		return false, resultLog
	}

	// check file exists
	existAndNotNull := FileExistAndNotNull(desFile)
	if !existAndNotNull {
		return false, []string{
			"[DownloadFileBySocks5] - file not exist  download error!",
		}
	}

	return true, resultLog
}
