// Copyright (C) 2019 Marius Schellenberger

package core

import (
	"fmt"
	"testing"
)

func TestParsePermString(t *testing.T) {
	data := map[string]Permission{
		"":     Invalid,
		"1":    Public,
		"2":    Private,
		"123":  Invalid,
		"test": Invalid,
	}
	for k, v := range data {
		t.Run(k, func(t *testing.T) {
			if ParsePermString(k) != v {
				t.Fail()
			}
		})
	}
}

func TestReadPerm(t *testing.T) {
	data := []struct {
		Username string
		Perm     Permission
		Section  Section
		OK       bool
	}{
		{"", Invalid, Section{Members: []string{"admin"}}, false},
		{"", Public, Section{Members: []string{"admin"}}, true},
		{"user", Public, Section{Members: []string{"admin"}}, true},
		{"", Private, Section{Members: []string{"admin"}}, false},
		{"user", Private, Section{Members: []string{"admin"}}, false},
		{"", Private, Section{Members: []string{"user"}}, false},
		{"user", Private, Section{Members: []string{"user"}}, true},
		{"user", Private, Section{Members: []string{"user", "admin"}}, true},
		{"admin", Private, Section{Members: []string{"user"}}, false},
	}
	for i, v := range data {
		t.Run(fmt.Sprintf("Read:%d", i), func(t *testing.T) {
			if ReadPerm(v.Username, v.Perm, v.Section) != v.OK {
				t.Fail()
			}
		})
	}
}

func TestWritePerm(t *testing.T) {
	data := []struct {
		Username string
		Perm     Permission
		Section  Section
		OK       bool
	}{
		{"", Invalid, Section{Members: []string{"user"}}, false},
		{"", Public, Section{Members: []string{"user"}}, false},
		{"user", Public, Section{Members: []string{"user"}}, true},
		{"user", Public, Section{Members: []string{"admin"}}, false},
		{"user", Private, Section{Members: []string{"user"}}, true},
		{"", Private, Section{Members: []string{"user"}}, false},
		{"", Private, Section{Members: []string{"user", "admin"}}, false},
		{"user", Private, Section{Members: []string{"user", "admin"}}, true},
		{"admin", Private, Section{Members: []string{"user", "admin"}}, true},
	}
	for i, v := range data {
		t.Run(fmt.Sprintf("Write:%d", i), func(t *testing.T) {
			if WritePerm(v.Username, v.Perm, v.Section) != v.OK {
				t.Fail()
			}
		})
	}
}
