package nixbuild

import (
	"context"
	"testing"

	"hg.lukegb.com/lukegb/depot/go/nix/nixpool"
	"hg.lukegb.com/lukegb/depot/go/nix/nixstore"
)

// DELETE ME
const remote = "ssh-ng://lukegb@localhost?insecure-allow-any-ssh-host-key=true&privkey=/home/lukegb/.ssh/id_ed25519"

// const storePath = "/nix/store/hx2qbqfjpv08w2aw6d5md6vnjwppzccb-golib-nixbuild"
const drvPath = "/nix/store/bi4dbkxdy94wk5qbqcq54rby0y0dql0j-ci.drv"

func TestPeerResolver(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	t.Cleanup(cancel)

	factory, err := nixpool.DaemonDialer(ctx, remote)
	if err != nil {
		t.Fatalf("DaemonDialer(%q): %v", remote, err)
	}
	pool := nixpool.New(ctx, factory, 1)
	builderPool := nixpool.New(ctx, factory, 1)
	d, err := factory()
	if err != nil {
		t.Fatalf("factory: %v", err)
	}
	d.Close()

	res := PeerResolver{PeerFetcher: PeerFetcher{pool}}
	drv, err := res.LoadDerivation(ctx, drvPath)
	if err != nil {
		t.Fatalf("LoadDerivation(%q): %v", drvPath, err)
	}
	bd, err := drv.ToBasicDerivation(ctx, res)
	if err != nil {
		t.Fatalf("drv.ToBasicDerivation(): %v", err)
	}

	at := nixstore.NewActivityTracker()
	cfg := Config{
		Target: &PeerTarget{
			PeerFetcher: PeerFetcher{
				Pool: pool,
			},
			ActivityTracker: at,
		},
		ResolveOnTarget: true,
		Resolvers: []Resolver{
			PeerResolver{PeerFetcher: PeerFetcher{pool}},
		},
		Builders:                      []*nixpool.Pool{builderPool},
		ResolveDependenciesOnBuilders: false,
	}
	coord := NewCoordinator(cfg, at)
	//wi := coord.AddWork(ctx, storePath)
	wi := coord.AddDerivationWork(ctx, bd, drvPath)
	<-wi.doneCh
}