package common

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

	"github.com/hekmon/transmissionrpc"
)

func GetResponse(url string) (io.ReadCloser, error) {
	req, _ := http.NewRequest("GET", url, nil)
	req.Header.Add("User-Agent", "go-torrent-helper")

	// Add required headers for GitHub API
	if strings.Contains(url, "github") {
		req.Header.Add("Accept", "application/vnd.github.v3.text-match+json")
		req.Header.Add("Accept", "application/vnd.github.moondragon+json")
	}

	// Carry out the request and receive response
	client := http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("Error while making request: %s\n", err)
	}

	// Status in <200 or >299
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return nil, fmt.Errorf("Error: %d %s\n", resp.StatusCode, resp.Status)
	}

	// Return response body
	return resp.Body, nil
}

func values[M ~map[K]V, K comparable, V any](m M) []V {
	r := make([]V, 0, len(m))
	for _, v := range m {
		r = append(r, v)
	}

	return r
}

func keys[M ~map[K]V, K comparable, V any](m M) []K {
	r := make([]K, 0, len(m))
	for k := range m {
		r = append(r, k)
	}

	return r
}

func RemoveTorrents(nameSubstr string, relver string, transmissionbt *transmissionrpc.Client) error {
	torrents, err := transmissionbt.TorrentGet([]string{"id", "name"}, nil)
	if err != nil {
		return err
	}

	torrentsMap := map[string]int64{}
	for _, torrent := range torrents {
		if relver != "*" {
			if strings.Contains(*torrent.Name, nameSubstr) && strings.Contains(*torrent.Name, relver) {
				torrentsMap[*torrent.Name] = *torrent.ID
			}
		} else {
			if strings.Contains(*torrent.Name, nameSubstr) {
				torrentsMap[*torrent.Name] = *torrent.ID
			}
		}
	}

	rmPayload := &transmissionrpc.TorrentRemovePayload{
		IDs:             values(torrentsMap),
		DeleteLocalData: true,
	}

	if err := transmissionbt.TorrentRemove(rmPayload); err != nil {
		return err
	}

	for _, key := range keys(torrentsMap) {
		log.Printf("%s removed\n", key)
	}

	return nil
}
