package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
)

// TODO: Add a semaphore to limit concurrent requests to 30
// Use a buffered channel as a semaphore

func main() {
	args := os.Args[1:]
	// Args might be a single string with line returns to delimit sites, break them apart
	if len(args) == 1 {
		args = strings.Split(args[0], "\n")
	}

	wg := &sync.WaitGroup{}
	wg.Add(len(args))

	now := time.Now()

	// TODO: Create a semaphore here with capacity of 30
	// sem := make(chan struct{}, 30)

	for _, a := range args {
		// TODO: Acquire the semaphore before launching goroutine
		// sem <- struct{}{}

		go get(a, wg /* TODO: pass semaphore to get function */)
	}

	wg.Wait()

	fmt.Printf("It took %s for the entire process to finish\n", time.Since(now))
}

// TODO: Update function signature to accept semaphore
func get(s string, wg *sync.WaitGroup) {
	defer wg.Done()
	// TODO: Release semaphore when done
	// defer func() { <-sem }()

	now := time.Now()

	_, err := http.Get(s)
	if err != nil {
		log.Printf("failed to retrieve %s: %s\n", s, err)
		return
	}
	log.Printf("Retrieved site %s in %s\n", s, time.Since(now))
}
