package tysc

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

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

// InsertSetDAO extends the type BaseDAO.
type InsertSetDAO struct {
	Db dao.BaseDAO
}

const (
	// INSERTSETCOLLECTION defines the collection name for storing insert sets.
	INSERTSETCOLLECTION = "insertSet"
	// INSERTSETMODEL defines the name of the insert set data model.
	INSERTSETMODEL = "kontor.tysc.insertSet"
)

// FindAll retrieves the list of cards from the database.
func (m *InsertSetDAO) FindAll() ([]InsertSet, error) {
	m.Db.Connect()
	var insertSets []InsertSet
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Find(bson.M{"model": INSERTSETMODEL}).All(&insertSets)
	return insertSets, err
}

// FindByID returns an card with given id or returns the error.
func (m *InsertSetDAO) FindByID(id string) (InsertSet, error) {
	m.Db.Connect()
	var insertSet InsertSet
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).FindId(bson.ObjectIdHex(id)).One(&insertSet)
	return insertSet, err
}

// FindByManufacturer returns a insert set with given manufacturer or returns the error.
func (m *InsertSetDAO) FindByManufacturer(manufacturer string) ([]InsertSet, error) {
	m.Db.Connect()
	var insertSets []InsertSet
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Find(bson.M{"model": INSERTSETMODEL, "manufacturer": bson.ObjectIdHex(manufacturer)}).All(&insertSets)
	return insertSets, err
}

// FindByName returns a insert set with given name or returns the error.
func (m *InsertSetDAO) FindByName(name string) (InsertSet, error) {
	m.Db.Connect()
	var insertSet InsertSet
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Find(bson.M{"name": name, "model": INSERTSETMODEL}).One(&insertSet)
	return insertSet, err
}

// Insert an insert set into database.
func (m *InsertSetDAO) Insert(insertSet InsertSet) error {
	m.Db.Connect()
	insertSet.Model = INSERTSETMODEL
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Insert(&insertSet)
	return err
}

// Upsert an insert set into database.
func (m *InsertSetDAO) Upsert(insertSet InsertSet) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	insertSet.Model = INSERTSETMODEL
	info, err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Upsert(bson.M{"name": insertSet.Name}, &insertSet)
	return info, err
}

// Update an existing insert set.
func (m *InsertSetDAO) Update(insertSet InsertSet) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).UpdateId(insertSet.ID, &insertSet)
	return err
}

// Delete an existing insert set.
func (m *InsertSetDAO) Delete(insertSet InsertSet) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(INSERTSETCOLLECTION).Remove(&insertSet)
	return err
}
