package mongolayer

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"nbarest/lib/persistence"
)

const(
	DB="myplayers"
	PLAYER="players"
)

func NewMongoDBLayer(connection string)(persistence.DatabaseHandler,error){
	s,err:=mgo.Dial(connection)
	if err!=nil{
		panic(err)
	}
	return &MongoDBLayer{session: s},err
}

type MongoDBLayer struct {
	session *mgo.Session
}

func (m *MongoDBLayer) AddPlayer(p persistence.Player)([]byte,error){
	s:=m.getFreshSession()
	defer s.Close()
	if !p.ID.Valid(){
		p.ID=bson.NewObjectId()
	}
	return []byte(p.ID),s.DB(DB).C(PLAYER).Insert(p)

}
func (m *MongoDBLayer) FindPlayer(id []byte)(persistence.Player,error){
	s:=m.getFreshSession()
	defer s.Close()
	p:= persistence.Player{}
	err:=s.DB(DB).C(PLAYER).FindId(bson.ObjectId(id)).One(&p)
	return p,err
}
func (m *MongoDBLayer) FindPlayerByName(name string)(persistence.Player,error){
	s:=m.getFreshSession()
	defer s.Close()
	p:= persistence.Player{}
	err:=s.DB(DB).C(PLAYER).Find(bson.M{"name": name}).One(&p)
	return p,err
}
func (m*MongoDBLayer) FindAllAvailablePlayers()([]persistence.Player,error){
	s:=m.getFreshSession()
	defer s.Close()
	ps:=[]persistence.Player{}
	err:=s.DB(DB).C(PLAYER).Find(nil).All(&ps)
	return ps,err
}

func (m *MongoDBLayer) getFreshSession() *mgo.Session{
	return m.session.Copy()
}