package parrot

import (
	"fmt"
	"log"
	"strings"

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

type Parrot struct {
	NameSubstr string
	Relver     string
	URL        string
}

func (p Parrot) AddNewTorrents(transmissionbt *transmissionrpc.Client) error {
	p.URL = fmt.Sprintf("https://deb.parrot.sh/direct///parrot/iso/%s/", p.Relver)
	respBody, err := common.GetResponse(p.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
	var torrentURLs []string
	doc.Find("a").Each(func(i int, s *goquery.Selection) {
		if strings.Contains(s.Text(), "torrent") {
			torrentURLs = append(torrentURLs, fmt.Sprintf("%s/%s", p.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 (p Parrot) RemoveOldTorrents(transmissionbt *transmissionrpc.Client) error {
	if err := common.RemoveTorrents(p.NameSubstr, p.Relver, transmissionbt); err != nil {
		return err
	}

	return nil
}
