package admin

import (
	"gitlab.thpeetz.de/kontor/kontor-go/pkg/dao"
	"reflect"
	"testing"

	"gopkg.in/mgo.v2/bson"
)

var userModelTestTable = []struct {
	name     string
	typeName string
}{
	{"Id", "string"},
	{"Email", "string"},
	{"Username", "string"},
	{"Firstname", "string"},
	{"Lastname", "string"},
	{"Password", "string"},
	{"IsAdmin", "bool"},
	{"Model", "string"},
}

func TestUserModel(t *testing.T) {
	m := User{}
	if reflect.TypeOf(m).NumField() != len(userModelTestTable) {
		t.Fail()
	}
	for index, testData := range userModelTestTable {
		givenType := reflect.TypeOf(m).Field(index).Type.Kind().String()
		if givenType != testData.typeName {
			t.Fail()
		}
	}
}

func TestListUsers(t *testing.T) {
	var userDao = UserDAO{Db: dao.TestDb}
	users, err := userDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if users != nil {
		t.Fail()
	}
}

func TestInsertUser(t *testing.T) {
	var (
		userDao = UserDAO{Db: dao.TestDb}
		user    = User{}
		users   []User
	)
	user.ID = bson.NewObjectId()
	user.Username = "test"
	err := userDao.Insert(user)
	if err != nil {
		t.Fail()
	}
	users, err = userDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(users) != 1 {
		t.Fail()
	}
}

func TestUpsertUser(t *testing.T) {
	var (
		userDao = UserDAO{Db: dao.TestDb}
		user    = User{}
	)
	user.ID = bson.NewObjectId()
	user.Username = "test2"
	userDao.Upsert(user)
	users, err := userDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(users) != 2 {
		t.Fail()
	}
}

func TestDeleteUser(t *testing.T) {
	var (
		userDao = UserDAO{Db: dao.TestDb}
	)
	users, err := userDao.FindAll()
	if err != nil {
		t.Fail()
	}
	for _, user := range users {
		userDao.Delete(user)
	}
	users, err = userDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(users) != 0 {
		t.Fail()
	}
}
