package library

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

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

var bookModelTestTable = []struct {
	name     string
	typeName string
}{
	{"Id", "string"},
	{"Title", "string"},
	{"Author", "string"},
	{"Publisher", "string"},
	{"Isbn", "string"},
	{"Year", "int"},
	{"Edition", "string"},
	{"Model", "string"},
}

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

func TestListBooks(t *testing.T) {
	var (
		bookDao = BookDAO{Db: dao.TestDb}
	)
	books, err := bookDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(books) != 0 {
		t.Fail()
	}
}

func TestInsertBook(t *testing.T) {
	var (
		bookDao = BookDAO{Db: dao.TestDb}
		book    = Book{}
		books   []Book
	)
	book.ID = bson.NewObjectId()
	book.Title = "Packt Publishing"
	err := bookDao.Insert(book)
	if err != nil {
		t.Fail()
	}
	books, err = bookDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(books) != 1 {
		t.Fail()
	}
}

func TestUpsertBook(t *testing.T) {
	var (
		bookDao = BookDAO{Db: dao.TestDb}
		book    = Book{}
	)
	book.ID = bson.NewObjectId()
	book.Title = "Hansa Verlag"
	bookDao.Upsert(book)
	books, err := bookDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(books) != 2 {
		t.Fail()
	}
}

func TestDeleteBook(t *testing.T) {
	var (
		bookDao = BookDAO{Db: dao.TestDb}
	)
	books, err := bookDao.FindAll()
	if err != nil {
		t.Fail()
	}
	for _, book := range books {
		bookDao.Delete(book)
	}
	books, err = bookDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(books) != 0 {
		t.Fail()
	}
}
