// meta4ra -- Metalink 4.0 utilities
// Copyright (C) 2021-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	meta4ra "go.stargrave.org/meta4ra/v2/internal"
)

func runDl() {
	progress := flag.Bool("progress", false, "Show progress of downloading")
	size := flag.Uint("size", 0, "Set expected size for -progress")
	flag.Usage = func() {
		fmt.Fprintf(flag.CommandLine.Output(),
			"Usage: %s [options] URL >data\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()

	if *showVersion {
		fmt.Println(meta4ra.Version())
		return
	}
	if *showWarranty {
		fmt.Println(meta4ra.Warranty)
		return
	}

	u, err := meta4ra.ParseURL(flag.Arg(0))
	if err != nil {
		log.Fatal(err)
	}
	client := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			fmt.Fprintf(os.Stderr, "redirect: %+q\n", req.URL.String())
			return nil
		},
	}
	resp, err := client.Get(u.URL)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprintln(os.Stderr, "headers:")
	for k := range resp.Header {
		for _, v := range resp.Header.Values(k) {
			fmt.Fprintf(os.Stderr, "\t%+q: %+q\n", k, v)
		}
	}
	if resp.StatusCode != http.StatusOK {
		log.Fatalln("status code:", resp.Status)
	}
	var sizeExpected uint64
	if *size == 0 {
		if resp.ContentLength > 0 {
			sizeExpected = uint64(resp.ContentLength)
		}
	} else {
		sizeExpected = uint64(*size)
	}
	var w io.Writer
	if *progress {
		bar := Progress{w: os.Stdout, now: time.Now(), total: sizeExpected}
		bar.next = bar.now.Add(ProgressPeriod)
		w = &bar
	} else {
		w = os.Stdout
	}
	_, err = io.Copy(w, bufio.NewReaderSize(resp.Body, meta4ra.BufLen))
	resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
}
