package freebsd

import (
	"bufio"
	"fmt"
	"log"
	"strings"

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

type FreeBSD struct {
	NameSubstr string
	Relver     string
	URL        string
}

func (fb FreeBSD) AddNewTorrents(transmissionbt *transmissionrpc.Client) error {
	fb.URL = fmt.Sprintf("https://people.freebsd.org/~jmg/FreeBSD-%s-R-magnet.txt", fb.Relver)
	respBody, err := common.GetResponse(fb.URL)
	if err != nil {
		return err
	}

	// Iterate throw lines of response body (FreeBSD-%s-R-magnet.txt)
	fileScanner := bufio.NewScanner(respBody)
	fileScanner.Split(bufio.ScanLines)
	var torrentURLs []string
	for fileScanner.Scan() {
		if strings.Contains(fileScanner.Text(), "magnet:?") {
			torrentURLs = append(torrentURLs, fileScanner.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 (fb FreeBSD) RemoveOldTorrents(transmissionbt *transmissionrpc.Client) error {
	if err := common.RemoveTorrents(fb.NameSubstr, fb.Relver, transmissionbt); err != nil {
		return err
	}

	return nil
}
