package model

import (
	"context"

	"git.kmsign.ru/royalcat/tstor/src/daemons/torrent"
	atorrent "github.com/anacrolix/torrent"
)

func Apply[I any, O any](in []I, f func(I) O) []O {
	out := make([]O, len(in))
	for i, v := range in {
		out[i] = f(v)
	}
	return out
}

func MapPeerSource(source atorrent.PeerSource) string {
	switch source {
	case atorrent.PeerSourceDirect:
		return "Direct"
	case atorrent.PeerSourceUtHolepunch:
		return "Ut Holepunch"
	case atorrent.PeerSourceDhtAnnouncePeer:
		return "DHT Announce"
	case atorrent.PeerSourceDhtGetPeers:
		return "DHT"
	case atorrent.PeerSourceIncoming:
		return "Incoming"
	case atorrent.PeerSourceTracker:
		return "Tracker"
	case atorrent.PeerSourcePex:
		return "PEX"
	default:
		return "Unknown"
	}
}

func MapTorrent(ctx context.Context, t *torrent.Controller) (*Torrent, error) {
	prio, err := t.Priority(ctx)
	if err != nil {
		return nil, err
	}

	return &Torrent{
		Infohash:       t.InfoHash(),
		Name:           t.Name(),
		BytesCompleted: t.BytesCompleted(),
		BytesMissing:   t.BytesMissing(),
		Priority:       prio,
		T:              t,
	}, nil
}

func MapTorrentStats(s torrent.TorrentStats) *TorrentStats {
	return &TorrentStats{
		Timestamp:        s.Timestamp,
		DownloadedBytes:  uint(s.DownloadedBytes),
		UploadedBytes:    uint(s.UploadedBytes),
		TotalPeers:       uint(s.TotalPeers),
		ActivePeers:      uint(s.ActivePeers),
		ConnectedSeeders: uint(s.ConnectedSeeders),
	}
}