package handler

import (
	"fmt"
	"github.com/anacrolix/torrent"
	"github.com/sirupsen/logrus"
	"os"
)

type Engine struct {
	client      *torrent.Client
	files       map[string]*MovieTorrent
	storagePath string
}

func NewEngine(storagePath string) (*Engine, error) {
	logrus.Info("Creating Streaming engine")
	if storagePath == "" {
		storagePath = os.TempDir()
		logrus.Debug("Storage path undefined. Using default temp directory")
	}
	logrus.Debugf("Storage Path: %s", storagePath)
	conf := torrent.NewDefaultClientConfig()
	conf.DataDir = storagePath
	c, err := torrent.NewClient(conf)
	if err != nil {
		return nil, err
	}
	return &Engine{c, map[string]*MovieTorrent{}, storagePath}, nil
}

func (e *Engine) Close() {
	e.client.Close()
}

func (e *Engine) Get(fileName string) (*MovieTorrent, error) {
	logrus.Infof("Requesting torrent: %s", fileName)
	if mt, ok := e.files[fileName]; ok {
		return mt, nil
	}
	return nil, fmt.Errorf("not found: %s", fileName)
}

func (e *Engine) Prepare(magnet string) error {
	logrus.Debugf("preparing magnet: %s", magnet)
	t, err := e.client.AddMagnet(magnet)
	if err != nil {
		return err
	}
	<-t.GotInfo()
	return nil
}
func (e *Engine) Download(magnet string) (*MovieTorrent, error) {
	logrus.Debugf("downloading magnet: %s", magnet)
	t, err := e.client.AddMagnet(magnet)
	if err != nil {
		return nil, err
	}
	<-t.GotInfo()
	file := getLargestFile(t)
	file.Download()
	mt := newMovieTorrent(file, t)
	mt.engine = e
	e.files[mt.FileName] = mt
	logrus.Infof("Downloading: %s", mt.FileName)
	return mt, nil
}

func getLargestFile(t *torrent.Torrent) *torrent.File {
	var target *torrent.File
	var maxSize int64

	for _, file := range t.Files() {
		if maxSize < file.Length() {
			maxSize = file.Length()
			target = file
		}
	}

	return target
}
