package tysc

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

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

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

const (
	// CARDSETCOLLECTION defines the collection name for storing cards sets.
	CARDSETCOLLECTION = "cardSet"
	// CARDSETMODEL defines the name of the card set data model.
	CARDSETMODEL = "kontor.tysc.cardSet"
)

// FindAll retrieves the list of card sets from the database.
func (m *CardSetDAO) FindAll() ([]CardSet, error) {
	m.Db.Connect()
	var cardSets []CardSet
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).Find(bson.M{"model": CARDSETMODEL}).All(&cardSets)
	return cardSets, err
}

// FindByID returns a card set with given id or returns the error.
func (m *CardSetDAO) FindByID(id string) (CardSet, error) {
	m.Db.Connect()
	var cardSet CardSet
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).FindId(bson.ObjectIdHex(id)).One(&cardSet)
	return cardSet, err
}

// FindByManufacturer returns a card set with given manufacturer or returns the error.
func (m *CardSetDAO) FindByManufacturer(manufacturer string) ([]CardSet, error) {
	m.Db.Connect()
	var cardSets []CardSet
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).Find(bson.M{"model": CARDSETMODEL, "manufacturer": bson.ObjectIdHex(manufacturer)}).All(&cardSets)
	return cardSets, err
}

// FindByName returns a card set with given name or returns the error.
func (m *CardSetDAO) FindByName(name string) (CardSet, error) {
	m.Db.Connect()
	var cardSet CardSet
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).Find(bson.M{"name": name, "model": CARDSETMODEL}).One(&cardSet)
	return cardSet, err
}

// Insert an card set into database.
func (m *CardSetDAO) Insert(cardSet CardSet) error {
	m.Db.Connect()
	cardSet.Model = CARDSETMODEL
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).Insert(&cardSet)
	return err
}

// Upsert an card set into database.
func (m *CardSetDAO) Upsert(cardSet CardSet) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	cardSet.Model = CARDSETMODEL
	info, err := m.Db.MongoDb.C(CARDSETCOLLECTION).Upsert(bson.M{"name": cardSet.Name}, &cardSet)
	return info, err
}

// Update an existing card set.
func (m *CardSetDAO) Update(cardSet CardSet) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).UpdateId(cardSet.ID, &cardSet)
	return err
}

// Delete an existing card set.
func (m *CardSetDAO) Delete(cardSet CardSet) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(CARDSETCOLLECTION).Remove(&cardSet)
	return err
}
