package library

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

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

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

const (
	// PUBLISHERCOLLECTION defines the collection name for storing publishers.
	PUBLISHERCOLLECTION = "publisher"
	// PUBLISHERMODEL defines the name of the publisher data model.
	PUBLISHERMODEL = "kontor.library.publisher"
)

// FindAll retrieves the list of publishers from the database.
func (m *PublisherDAO) FindAll() ([]Publisher, error) {
	m.Db.Connect()
	var publishers []Publisher
	err := m.Db.MongoDb.C(PUBLISHERCOLLECTION).Find(bson.M{"model": PUBLISHERMODEL}).All(&publishers)
	return publishers, err
}

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

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

// Insert a publisher into database.
func (m *PublisherDAO) Insert(publisher Publisher) error {
	m.Db.Connect()
	publisher.Model = PUBLISHERMODEL
	err := m.Db.MongoDb.C(PUBLISHERCOLLECTION).Insert(&publisher)
	return err
}

// Upsert a publisher into database.
func (m *PublisherDAO) Upsert(publisher Publisher) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	publisher.Model = PUBLISHERMODEL
	info, err := m.Db.MongoDb.C(PUBLISHERCOLLECTION).Upsert(bson.M{"name": publisher.Name}, &publisher)
	return info, err
}

// Delete an existing publisher.
func (m *PublisherDAO) Delete(publisher Publisher) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(PUBLISHERCOLLECTION).Remove(&publisher)
	return err
}

// Update an existing publisher.
func (m *PublisherDAO) Update(publisher Publisher) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(PUBLISHERCOLLECTION).UpdateId(publisher.ID, &publisher)
	return err
}
