package library

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

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

var publisherModelTestTable = []struct {
	name     string
	typeName string
}{
	{"Id", "string"},
	{"Name", "string"},
	{"Model", "string"},
}

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

	}
}

func TestListPublishers(t *testing.T) {
	var (
		publisherDao = PublisherDAO{Db: dao.TestDb}
	)
	publishers, err := publisherDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(publishers) != 0 {
		t.Fail()
	}
}

func TestInsertPublisher(t *testing.T) {
	var (
		publisherDao = PublisherDAO{Db: dao.TestDb}
		publisher    = Publisher{}
		publishers   []Publisher
	)
	publisher.ID = bson.NewObjectId()
	publisher.Name = "Packt Publishing"
	err := publisherDao.Insert(publisher)
	if err != nil {
		t.Fail()
	}
	publishers, err = publisherDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(publishers) != 1 {
		t.Fail()
	}
}

func TestUpsertPublisher(t *testing.T) {
	var (
		publisherDao = PublisherDAO{Db: dao.TestDb}
		publisher    = Publisher{}
	)
	publisher.ID = bson.NewObjectId()
	publisher.Name = "Hansa Verlag"
	publisherDao.Upsert(publisher)
	publishers, err := publisherDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(publishers) != 2 {
		t.Fail()
	}
}

func TestDeletePublisher(t *testing.T) {
	var (
		publisherDao = PublisherDAO{Db: dao.TestDb}
	)
	publishers, err := publisherDao.FindAll()
	if err != nil {
		t.Fail()
	}
	for _, publisher := range publishers {
		publisherDao.Delete(publisher)
	}
	publishers, err = publisherDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(publishers) != 0 {
		t.Fail()
	}
}
