package rocky

import (
	"fmt"
	"log"
	"strings"

	"codeberg.org/hyperreal/go-torrent-helper/common"
	"github.com/PuerkitoBio/goquery"
	"github.com/hekmon/transmissionrpc"
)

type Rocky struct {
	NameSubstr string
	Relver     string
	URL        string
}

func (r Rocky) AddNewTorrents(transmissionbt *transmissionrpc.Client) error {
	// Set torrentURLs for Rocky Linux mirror
	archs := []string{"aarch64", "ppc64le", "s390x", "x86_64"}
	var torrentURLs []string

	// Iterate over architectures and extract torrent URLs for each
	for _, arch := range archs {
		r.URL = fmt.Sprintf("https://download.rockylinux.org/pub/rocky/%s/isos/%s/", r.Relver, arch)
		respBody, err := common.GetResponse(r.URL)
		if err != nil {
			return err
		}

		// Get a goquery doc from response body
		doc, err := goquery.NewDocumentFromReader(respBody)
		if err != nil {
			return err
		}

		// Extract torrent URLs from web page contents
		doc.Find("a").Each(func(i int, s *goquery.Selection) {
			if strings.Contains(s.Text(), "torrent") {
				torrentURLs = append(torrentURLs, fmt.Sprintf("%s/%s", r.URL, s.Text()))
			}
		})
	}

	// Add torrents to Transmission instance
	for _, torrentURL := range torrentURLs {
		torrent, err := transmissionbt.TorrentAdd(&transmissionrpc.TorrentAddPayload{
			Filename: &torrentURL,
		})
		if err != nil {
			return err
		}

		log.Printf("%s added\n", *torrent.Name)
	}

	return nil
}

func (r Rocky) RemoveOldTorrents(transmissionbt *transmissionrpc.Client) error {
	if err := common.RemoveTorrents(r.NameSubstr, r.Relver, transmissionbt); err != nil {
		return err
	}

	return nil
}
