package tysc

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

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

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

const (
	// CARDCOLLECTION defines the collection name for storing cards.
	CARDCOLLECTION = "card"
	// CARDMODEL defines the name of the card data model.
	CARDMODEL = "kontor.tysc.card"
)

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

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

// Insert a card into database.
func (m *CardDAO) Insert(card Card) error {
	m.Db.Connect()
	card.Model = CARDMODEL
	err := m.Db.MongoDb.C(CARDCOLLECTION).Insert(&card)
	return err
}

// Upsert a card into database.
func (m *CardDAO) Upsert(card Card) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	card.Model = CARDMODEL
	info, err := m.Db.MongoDb.C(CARDCOLLECTION).Upsert(bson.M{"number": card.Number}, &card)
	return info, err
}

// Update an existing card.
func (m *CardDAO) Update(card Card) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(CARDCOLLECTION).UpdateId(card.ID, &card)
	return err
}

// Delete an existing card.
func (m *CardDAO) Delete(card Card) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(CARDCOLLECTION).Remove(&card)
	return err
}
