//go:build linux

package sched_test

import (
	"fmt"
	"runtime"
	"testing"

	"github.com/alexfalkowski/go-linux/v2/internal/test"
	"github.com/alexfalkowski/go-linux/v2/sched"
)

func ExampleAffinity() {
	allowed, err := sched.Affinity()
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(allowed.Count() > 0)
	// Output: true
}

// The worker checks that its effective set contains just the selected CPU.
//
//	true
func ExampleSetAffinity() {
	done := make(chan struct{})
	go func() {
		defer close(done)
		runtime.LockOSThread() // Keep the worker locked until it exits.

		allowed, err := sched.Affinity()
		if err != nil {
			fmt.Println(err)
			return
		}
		cpu := allowed.CPUs()[0]
		set, err := sched.NewCPUSet(cpu)
		if err != nil {
			fmt.Println(err)
			return
		}
		if err := sched.SetAffinity(set); err != nil {
			fmt.Println(err)
			return
		}

		// Run the work synchronously on this goroutine.
		effective, err := sched.Affinity()
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(effective.Count() == 1 && effective.Contains(cpu))
	}()
	<-done
}

func TestSetAffinityExample(t *testing.T) {
	test.RequireExampleOutput(t, ExampleSetAffinity, "true")
}

// The worker reads back its block I/O priority after applying it.
//
//	true
func ExampleSetScheduling() {
	done := make(chan struct{})
	go func() {
		defer close(done)
		runtime.LockOSThread()

		if err := sched.SetScheduling(sched.Attributes{Policy: sched.Batch, Nice: 19}); err != nil {
			fmt.Println(err)
			return
		}
		priority := sched.IOPriority{Class: sched.IOBestEffort, Level: 6}
		if err := sched.SetIOPriority(priority); err != nil {
			fmt.Println(err)
			return
		}

		// Run background storage work synchronously on this goroutine.
		observed, err := sched.GetIOPriority()
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(observed == priority)
	}()
	<-done
}

func TestSetSchedulingExample(t *testing.T) {
	test.RequireExampleOutput(t, ExampleSetScheduling, "true")
}
