package library

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

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

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

const (
	// BOOKCOLLECTION defines the collection name for storing books.
	BOOKCOLLECTION = "book"
	// BOOKMODEL defines the name of the book data model.
	BOOKMODEL = "kontor.library.book"
)

// FindAll retrieves the list of books from the database.
func (m *BookDAO) FindAll() ([]Book, error) {
	m.Db.Connect()
	var books []Book
	err := m.Db.MongoDb.C(BOOKCOLLECTION).Find(bson.M{"model": BOOKMODEL}).All(&books)
	return books, err
}

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

// FindByTitle returns a book with given title or returns the error.
func (m *BookDAO) FindByTitle(title string) (Book, error) {
	m.Db.Connect()
	var book Book
	err := m.Db.MongoDb.C(BOOKCOLLECTION).Find(bson.M{"title": title, "model": BOOKMODEL}).One(&book)
	return book, err
}

// Insert a book into database.
func (m *BookDAO) Insert(book Book) error {
	m.Db.Connect()
	book.Model = BOOKMODEL
	err := m.Db.MongoDb.C(BOOKCOLLECTION).Insert(&book)
	return err
}

// Upsert a book into database.
func (m *BookDAO) Upsert(book Book) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	book.Model = BOOKMODEL
	info, err := m.Db.MongoDb.C(BOOKCOLLECTION).Upsert(bson.M{"title": book.Title}, &book)
	return info, err
}

// Delete an existing book.
func (m *BookDAO) Delete(book Book) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(BOOKCOLLECTION).Remove(&book)
	return err
}

// Update an existing book.
func (m *BookDAO) Update(book Book) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(BOOKCOLLECTION).UpdateId(book.ID, &book)
	return err
}
