package download

import (
	"archive/zip"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
)

type Downloader struct {
	io.Reader
	Total   int64
	Current int64
}

func (d *Downloader) Read(p []byte) (n int, err error) {
	n, err = d.Reader.Read(p)
	d.Current += int64(n)
	fmt.Printf("\r正在下载，下载进度：%.2f%%", float64(d.Current*10000/d.Total)/100)
	if d.Current == d.Total {
		fmt.Printf("\r下载完成，下载进度：%.2f%%", float64(d.Current*10000/d.Total)/100)
	}
	return
}

func DownloadFile(url, filePath string) error {
	defer wg.Done()
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	file, _ := os.Create(filePath)
	defer func() {
		_ = file.Close()
	}()
	downloader := &Downloader{
		Reader: resp.Body,
		Total:  resp.ContentLength,
	}
	if _, err := io.Copy(file, downloader); err != nil {
		return err
	}
	return nil
}

var wg sync.WaitGroup

// func main() {
// 	task := make(map[string]string)
// 	task["https://dl.softmgr.qq.com/original/game/WeGameSetup3.32.4.6183_gjwegame_0_0.exe"] = "wegame.exe"
// 	for k, v := range task {
// 		// wg.Add(1)
// 		downloadFile(k, v)
// 	}
// 	// wg.Wait()
// }

func DownloadExe(appExe, url string) error {
	fmt.Println("download url => ", url)
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if path.Ext(url) == ".zip" {
		fmt.Println("not zip")
		bytes, err := io.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		appExeDir, _ := filepath.Split(appExe)
		err = UnzipByte(bytes, appExeDir, appExe)
		if err != nil {
			return err
		}
		return nil
	}

	fmt.Println("not zip")
	// 创建一个文件用于保存
	out, err := os.Create(appExe)
	if err != nil {
		return err
	}
	defer out.Close()

	// 然后将响应流和文件流对接起来
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}
	return nil
}

func UnzipByte(zipData []byte, dstDir string, appexe string) error {
	total := len(zipData)
	zipReader, err := zip.NewReader(strings.NewReader(string(zipData)), int64(total))
	if err != nil {
		return err
	}
	for _, file := range zipReader.File {

		if file.FileInfo().IsDir() {
			err := os.MkdirAll(file.Name, 0644)
			if err != nil {
				fmt.Println(err)
			}
			continue
		}
		//为文件时，打开文件
		zipFile, err := file.Open()

		//文件为空的时候，打印错误
		if err != nil {
			fmt.Println(err)
			continue
		}
		//这里在控制台输出文件的文件名及路径
		fmt.Println("unzip: ", file.Name)

		//在对应的目录中创建相同的文件
		NewFile, err := os.Create(appexe)
		if err != nil {
			fmt.Println(err)
			continue
		}
		//将内容复制
		io.Copy(NewFile, zipFile)
		//关闭文件
		NewFile.Close()
		zipFile.Close()

	}
	return nil
}
