package comics

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

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

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

const (
	// COMICCOLLECTION defines the collection name for storing comics.
	COMICCOLLECTION = "comic"
	// COMICMODEL defines the name of the comic data model.
	COMICMODEL = "kontor.comics.comic"
)

// FindAll retrieves the list of comisc from the database.
func (m *ComicDAO) FindAll() ([]Comic, error) {
	m.Db.Connect()
	var comics []Comic
	err := m.Db.MongoDb.C(COMICCOLLECTION).Find(bson.M{"model": COMICMODEL}).All(&comics)
	return comics, err
}

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

// FindByName returns an comic with given name or returns the error.
func (m *ComicDAO) FindByName(name string) (Comic, error) {
	m.Db.Connect()
	var comic Comic
	err := m.Db.MongoDb.C(COMICCOLLECTION).Find(bson.M{"name": name, "model": COMICMODEL}).One(&comic)
	return comic, err
}

// Insert a comic into database.
func (m *ComicDAO) Insert(comic Comic) error {
	m.Db.Connect()
	comic.Model = COMICMODEL
	err := m.Db.MongoDb.C(COMICCOLLECTION).Insert(&comic)
	//util.PrintDebug("ComicDAO.Insert: %v", comic)
	return err
}

// Upsert a comic into database.
func (m *ComicDAO) Upsert(comic Comic) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	comic.Model = COMICMODEL
	info, err := m.Db.MongoDb.C(COMICCOLLECTION).Upsert(bson.M{"title": comic.Title}, &comic)
	return info, err
}

// Delete an existing comic.
func (m *ComicDAO) Delete(comic Comic) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(COMICCOLLECTION).Remove(&comic)
	return err
}

// Update an existing movie
func (m *ComicDAO) Update(comic Comic) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(COMICCOLLECTION).UpdateId(comic.ID, &comic)
	return err
}
