package main

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

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

const BlockSize = 1024

func HttpDownload(path string, out io.Writer, ctx context.Context) error {
	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 {
		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")
	}
	return nil
}