package tysc

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

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

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

const (
	// TEAMCOLLECTION defines the collection name for storing teams.
	TEAMCOLLECTION = "team"
	// TEAMMODEL defines the name of the team data model.
	TEAMMODEL = "kontor.tysc.team"
)

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

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

// FindByName returns a team with given name or returns the error.
func (m *TeamDAO) FindByName(name string) (Team, error) {
	m.Db.Connect()
	var team Team
	err := m.Db.MongoDb.C(TEAMCOLLECTION).Find(bson.M{"name": name, "model": TEAMMODEL}).One(&team)
	return team, err
}

// Insert a team into database
func (m *TeamDAO) Insert(team Team) error {
	m.Db.Connect()
	team.Model = TEAMMODEL
	err := m.Db.MongoDb.C(TEAMCOLLECTION).Insert(&team)
	return err
}

// Upsert a team into database
func (m *TeamDAO) Upsert(team Team) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	team.Model = TEAMMODEL
	info, err := m.Db.MongoDb.C(TEAMCOLLECTION).Upsert(bson.M{"name": team.Name}, &team)
	return info, err
}

// Update an existing team.
func (m *TeamDAO) Update(team Team) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(TEAMCOLLECTION).UpdateId(team.ID, &team)
	return err
}

// Delete an existing team.
func (m *TeamDAO) Delete(team Team) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(TEAMCOLLECTION).Remove(&team)
	return err
}
