package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/url"
	"os"
	"path/filepath"
)

const (
	envVarURL    = "SEND2GOKAPI_URL"
	envVarAPIKey = "SEND2GOKAPI_API_KEY"

	keyEscape = 27
)

func main() {
	flagDownloads := flag.Int("d", 5, "Max number of downloads")
	flagDays := flag.Int("t", 7, "Amount of time to keep file, in days")
	flag.Parse()

	if flag.NArg() < 1 {
		flag.Usage()
		os.Exit(2)
	}

	config := Config{
		Hostname:       os.Getenv(envVarURL),
		APIKey:         os.Getenv(envVarAPIKey),
		ParallelChunks: 4,
		ChunkSize:      1024 * 100,
		MaxDownloads:   max(*flagDownloads, 0),
		MaxDays:        max(*flagDays, 0),
	}
	if config.Hostname == "" || config.APIKey == "" {
		fmt.Fprintf(flag.CommandLine.Output(), "Please set the following environment variables:\n")
		envVarUsage()
		os.Exit(2)
	}

	hostUrl, err := url.Parse(config.Hostname)
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	client := newGokapiClient(hostUrl, config.APIKey)
	cnkr := newChunker(client, config)

	maxFileLen := 0
	for _, file := range flag.Args() {
		maxFileLen = max(maxFileLen, len(filepath.Base(file)))
	}

	for _, file := range flag.Args() {
		ur, err := cnkr.UploadFile(ctx, file, progressBarReport(file, maxFileLen))
		if err == nil {
			displayCompletion(file, maxFileLen, ur)
		} else {
			displayFailedCompletion(file, maxFileLen, err)
		}
	}
}