package tysc

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

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

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

const (
	// PLAYERCOLLECTION defines the collection name for storing players.
	PLAYERCOLLECTION = "player"
	// PLAYERMODEL defines the name of the player data model.
	PLAYERMODEL = "kontor.tysc.player"
)

// FindAll retrieves the list of players from the database.
func (m *PlayerDAO) FindAll() ([]Player, error) {
	m.Db.Connect()
	var players []Player
	err := m.Db.MongoDb.C(PLAYERCOLLECTION).Find(bson.M{"model": PLAYERMODEL}).All(&players)
	return players, err
}

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

// FindByLastName returns a player with given last name or returns the error.
func (m *PlayerDAO) FindByLastName(lastname string) (Player, error) {
	m.Db.Connect()
	var player Player
	err := m.Db.MongoDb.C(PLAYERCOLLECTION).Find(bson.M{"lastname": lastname, "model": PLAYERMODEL}).One(&player)
	return player, err
}

// Insert a player into database.
func (m *PlayerDAO) Insert(player Player) error {
	m.Db.Connect()
	player.Model = PLAYERMODEL
	err := m.Db.MongoDb.C(PLAYERCOLLECTION).Insert(&player)
	return err
}

// Upsert a player into database.
func (m *PlayerDAO) Upsert(player Player) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	player.Model = PLAYERMODEL
	info, err := m.Db.MongoDb.C(PLAYERCOLLECTION).Upsert(bson.M{"lastname": player.Lastname}, &player)
	return info, err
}

// Update an existing player.
func (m *PlayerDAO) Update(player Player) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(PLAYERCOLLECTION).UpdateId(player.ID, &player)
	return err
}

// Delete an existing player.
func (m *PlayerDAO) Delete(player Player) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(PLAYERCOLLECTION).Remove(&player)
	return err
}
