package resolver

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.43

import (
	"context"

	graph "git.kmsign.ru/royalcat/tstor/src/delivery/graphql"
	"git.kmsign.ru/royalcat/tstor/src/delivery/graphql/model"
	"git.kmsign.ru/royalcat/tstor/src/host/vfs"
)

// Torrents is the resolver for the torrents field.
func (r *queryResolver) Torrents(ctx context.Context, filter *model.TorrentsFilter, pagination *model.Pagination) ([]*model.Torrent, error) {
	torrents, err := r.Service.ListTorrents(ctx)
	if err != nil {
		return nil, err
	}

	filterFuncs := []func(torrent *model.Torrent) bool{}

	if filter != nil {
		if filter.BytesCompleted != nil {
			filterFuncs = append(filterFuncs, func(torrent *model.Torrent) bool {
				return filter.BytesCompleted.Include(torrent.BytesCompleted)
			})
		}
		if filter.BytesMissing != nil {
			filterFuncs = append(filterFuncs, func(torrent *model.Torrent) bool {
				return filter.BytesMissing.Include(torrent.BytesMissing)
			})
		}
		if filter.PeersCount != nil {
			filterFuncs = append(filterFuncs, func(torrent *model.Torrent) bool {
				return filter.PeersCount.Include(
					int64(len(torrent.T.Torrent().PeerConns())),
				)
			})
		}

	}

	filterFunc := func(torrent *model.Torrent) bool {
		for _, f := range filterFuncs {
			if !f(torrent) {
				return false
			}
		}
		return true
	}

	tr := []*model.Torrent{}
	for _, t := range torrents {
		d := model.MapTorrent(t)

		if !filterFunc(d) {
			continue
		}
		tr = append(tr, d)
	}

	return tr, nil
}

// FsListDir is the resolver for the fsListDir field.
func (r *queryResolver) FsListDir(ctx context.Context, path string) ([]model.DirEntry, error) {
	entries, err := r.VFS.ReadDir(path)
	if err != nil {
		return nil, err
	}
	out := []model.DirEntry{}
	for _, e := range entries {
		switch e.(type) {
		case *vfs.TorrentFs:
			e := e.(*vfs.TorrentFs)
			out = append(out, model.TorrentFs{
				Name:    e.Name(),
				Torrent: model.MapTorrent(e.Torrent),
			})
		default:
			if e.IsDir() {
				out = append(out, model.Dir{Name: e.Name()})
			} else {
				info, err := e.Info()
				if err != nil {
					return nil, err
				}

				out = append(out, model.File{
					Name: e.Name(),
					Size: info.Size(),
				})
			}
		}

	}

	return out, nil
}

// Query returns graph.QueryResolver implementation.
func (r *Resolver) Query() graph.QueryResolver { return &queryResolver{r} }

type queryResolver struct{ *Resolver }