package tysc

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

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

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

const (
	// SPORTCOLLECTION defines the collection name for storing sports.
	SPORTCOLLECTION = "sport"
	// SPORTMODEL defines the name of the sport data model.
	SPORTMODEL = "kontor.tysc.sport"
)

// FindAll retrieves the list of sports from the database.
func (m *SportDAO) FindAll() ([]Sport, error) {
	m.Db.Connect()
	var sports []Sport
	err := m.Db.MongoDb.C(SPORTCOLLECTION).Find(bson.M{"model": SPORTMODEL}).All(&sports)
	return sports, err
}

// FindByID returns a sport with given id or returns the error.
func (m *SportDAO) FindByID(id string) (Sport, error) {
	m.Db.Connect()
	var sport Sport
	err := m.Db.MongoDb.C(SPORTCOLLECTION).FindId(bson.ObjectIdHex(id)).One(&sport)
	return sport, err
}

// FindByName returns a sport with given name or returns the error.
func (m *SportDAO) FindByName(name string) (Sport, error) {
	m.Db.Connect()
	var sport Sport
	err := m.Db.MongoDb.C(SPORTCOLLECTION).Find(bson.M{"name": name, "model": SPORTMODEL}).One(&sport)
	return sport, err
}

// Insert a sport into database.
func (m *SportDAO) Insert(sport Sport) error {
	m.Db.Connect()
	sport.Model = SPORTMODEL
	err := m.Db.MongoDb.C(SPORTCOLLECTION).Insert(&sport)
	return err
}

// Upsert a sport into database.
func (m *SportDAO) Upsert(sport Sport) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	sport.Model = SPORTMODEL
	info, err := m.Db.MongoDb.C(SPORTCOLLECTION).Upsert(bson.M{"name": sport.Name}, &sport)
	return info, err
}

// Update an existing sport.
func (m *SportDAO) Update(sport Sport) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(SPORTCOLLECTION).UpdateId(sport.ID, &sport)
	return err
}

// Delete an existing sport.
func (m *SportDAO) Delete(sport Sport) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(SPORTCOLLECTION).Remove(&sport)
	return err
}
