package ext_test

import (
	"encoding/json"
	"errors"
	"math"
	"reflect"
	"syscall"
	"testing"

	"hakurei.app/ext"
)

func TestSchedPolicyJSON(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		policy    ext.SchedPolicy
		want      string
		encodeErr error
		decodeErr error
	}{
		{ext.SCHED_NORMAL, `""`, nil, nil},
		{ext.SCHED_FIFO, `"fifo"`, nil, nil},
		{ext.SCHED_RR, `"rr"`, nil, nil},
		{ext.SCHED_BATCH, `"batch"`, nil, nil},
		{4, `"invalid policy 4"`, syscall.EINVAL, ext.InvalidSchedPolicyError("invalid policy 4")},
		{ext.SCHED_IDLE, `"idle"`, nil, nil},
		{ext.SCHED_DEADLINE, `"deadline"`, nil, nil},
		{ext.SCHED_EXT, `"ext"`, nil, nil},
		{math.MaxInt, `"iso"`, syscall.EINVAL, ext.InvalidSchedPolicyError("iso")},
	}
	for _, tc := range testCases {
		name := tc.policy.String()
		if tc.policy == ext.SCHED_NORMAL {
			name = "normal"
		}

		t.Run(name, func(t *testing.T) {
			t.Parallel()

			got, err := json.Marshal(tc.policy)
			if !errors.Is(err, tc.encodeErr) {
				t.Fatalf("Marshal: error = %v, want %v", err, tc.encodeErr)
			}
			if err == nil && string(got) != tc.want {
				t.Fatalf("Marshal: %s, want %s", string(got), tc.want)
			}

			var v ext.SchedPolicy
			if err = json.Unmarshal([]byte(tc.want), &v); !reflect.DeepEqual(err, tc.decodeErr) {
				t.Fatalf("Unmarshal: error = %v, want %v", err, tc.decodeErr)
			}
			if err == nil && v != tc.policy {
				t.Fatalf("Unmarshal: %d, want %d", v, tc.policy)
			}
		})
	}
}

func TestSchedPolicyMinMax(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		policy   ext.SchedPolicy
		min, max ext.Int
		err      error
	}{
		{ext.SCHED_NORMAL, 0, 0, nil},
		{ext.SCHED_FIFO, 1, 99, nil},
		{ext.SCHED_RR, 1, 99, nil},
		{ext.SCHED_BATCH, 0, 0, nil},
		{4, -1, -1, syscall.EINVAL},
		{ext.SCHED_IDLE, 0, 0, nil},
		{ext.SCHED_DEADLINE, 0, 0, nil},
		{ext.SCHED_EXT, 0, 0, nil},
	}
	for _, tc := range testCases {
		name := tc.policy.String()
		if tc.policy == ext.SCHED_NORMAL {
			name = "normal"
		}

		t.Run(name, func(t *testing.T) {
			t.Parallel()

			if priority, err := tc.policy.GetPriorityMax(); !reflect.DeepEqual(err, tc.err) {
				t.Fatalf("GetPriorityMax: error = %v, want %v", err, tc.err)
			} else if priority != tc.max {
				t.Fatalf("GetPriorityMax: %d, want %d", priority, tc.max)
			}
			if priority, err := tc.policy.GetPriorityMin(); !reflect.DeepEqual(err, tc.err) {
				t.Fatalf("GetPriorityMin: error = %v, want %v", err, tc.err)
			} else if priority != tc.min {
				t.Fatalf("GetPriorityMin: %d, want %d", priority, tc.min)
			}
		})
	}
}
