package comics

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

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

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

const (
	// ARTISTCOLLECTION defines the collection name for storing comic artists.
	ARTISTCOLLECTION = "artist"
	// ARTISTMODEL defines the name of the artist data model.
	ARTISTMODEL = "kontor.comics.artist"
)

// FindAll retrieves the list of artists from the database.
func (m *ArtistDAO) FindAll() ([]Artist, error) {
	m.Db.Connect()
	var artists []Artist
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).Find(bson.M{"model": ARTISTMODEL}).All(&artists)
	return artists, err
}

// FindByID returns an artists with given id or returns the error.
func (m *ArtistDAO) FindByID(id string) (Artist, error) {
	m.Db.Connect()
	var artist Artist
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).FindId(bson.ObjectIdHex(id)).One(&artist)
	return artist, err
}

// FindByName returns an artists with given name or returns the error.
func (m *ArtistDAO) FindByName(name string) (Artist, error) {
	m.Db.Connect()
	var artist Artist
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).Find(bson.M{"name": name, "model": ARTISTMODEL}).One(&artist)
	return artist, err
}

// Insert an artist into database.
func (m *ArtistDAO) Insert(artist Artist) error {
	m.Db.Connect()
	artist.Model = ARTISTMODEL
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).Insert(&artist)
	return err
}

// Upsert an artist into database.
func (m *ArtistDAO) Upsert(artist Artist) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	artist.Model = ARTISTMODEL
	info, err := m.Db.MongoDb.C(ARTISTCOLLECTION).Upsert(bson.M{"name": artist.Name}, &artist)
	return info, err
}

// Delete an existing artist.
func (m *ArtistDAO) Delete(artist Artist) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).Remove(&artist)
	if err != nil {
		log.Printf("ArtistDao.Delete: %v", err)
	}
	return err
}

// Update an existing artist.
func (m *ArtistDAO) Update(artist Artist) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(ARTISTCOLLECTION).UpdateId(artist.ID, &artist)
	return err
}
