package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

const BlockSize = 1024 * 64

func HttpDownload(path string, out io.Writer, ctx context.Context) error {
	path = strings.ReplaceAll(path, "\\", "/")
	res, err := http.Get("https://gitea.piwalker.net/fclauncher/" + path)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	var read int64 = 0
	for (read < res.ContentLength) || res.ContentLength == -1 {
		count, err := io.CopyN(out, res.Body, BlockSize)
		read += count
		if err != nil {
			break
		}
		if ctx != nil {
			runtime.EventsEmit(ctx, "download", read, res.ContentLength)
		}
	}
	if ctx != nil {
		runtime.EventsEmit(ctx, "download_complete")
	}
	fmt.Printf("Downloaded %d Bytes from %s, expected %d Bytes\n", read, path, res.ContentLength)
	return nil
}
