package tysc

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

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

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

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

func TestListManufacturers(t *testing.T) {
	var (
		manufacturerDao = ManufacturerDAO{Db: dao.TestDb}
	)
	manufacturers, err := manufacturerDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(manufacturers) != 0 {
		t.Fail()
	}
}

func TestInsertManufacturer(t *testing.T) {
	var (
		manufacturerDao = ManufacturerDAO{Db: dao.TestDb}
		manufacturer    = Manufacturer{}
		manufacturers   []Manufacturer
	)
	manufacturer.ID = bson.NewObjectId()
	manufacturer.Name = "test"
	err := manufacturerDao.Insert(manufacturer)
	if err != nil {
		t.Fail()
	}
	manufacturers, err = manufacturerDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(manufacturers) != 1 {
		t.Fail()
	}
}

func TestUpsertManufacturer(t *testing.T) {
	var (
		manufacturerDao = ManufacturerDAO{Db: dao.TestDb}
		manufacturer    = Manufacturer{}
	)
	manufacturer.ID = bson.NewObjectId()
	manufacturer.Name = "test2"
	manufacturerDao.Upsert(manufacturer)
	manufacturers, err := manufacturerDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(manufacturers) != 2 {
		t.Fail()
	}
}

func TestDeleteManufacturer(t *testing.T) {
	var (
		manufacturerDao = ManufacturerDAO{Db: dao.TestDb}
	)
	manufacturers, err := manufacturerDao.FindAll()
	if err != nil {
		t.Fail()
	}
	for _, manufacturer := range manufacturers {
		manufacturerDao.Delete(manufacturer)
	}
	manufacturers, err = manufacturerDao.FindAll()
	if err != nil {
		t.Fail()
	}
	if len(manufacturers) != 0 {
		t.Fail()
	}
}
