package nixos

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"

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

type Nixos struct {
	NameSubstr string
	Relver     string
	URL        string
}

func (n Nixos) AddNewTorrents(transmissionbt *transmissionrpc.Client) error {
	// Send GET request and receive HTTP response
	n.URL = "https://api.github.com/repos/AnimMouse/NixOS-ISO-Torrents/releases/latest"
	respBody, err := common.GetResponse(n.URL)
	if err != nil {
		return err
	}

	dataInBytes, err := ioutil.ReadAll(respBody)
	if err != nil {
		return fmt.Errorf("Error reading response body: %s\n", err)
	}

	result := make(map[string]interface{})
	if err := json.Unmarshal(dataInBytes, &result); err != nil {
		return err
	}

	// Get torrent URLs from HTTP response result
	var torrentURLs []interface{}
	for _, asset := range result["assets"].([]interface{}) {
		torrentURLs = append(torrentURLs, asset.(map[string]interface{})["browser_download_url"])
	}

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

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

	return nil
}

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

	return nil
}
