package tysc

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

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

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

const (
	// MANUFACTURERCOLLECTION defines the collection name for storing manufacturers.
	MANUFACTURERCOLLECTION = "manufacturer"
	// MANUFACTURERMODEL defines the name of the manufacturer data model.
	MANUFACTURERMODEL = "kontor.tysc.manufacturer"
)

// FindAll retrieves the list of manufacturers from the database.
func (m *ManufacturerDAO) FindAll() ([]Manufacturer, error) {
	m.Db.Connect()
	var manufacturers []Manufacturer
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).Find(bson.M{"model": MANUFACTURERMODEL}).All(&manufacturers)
	return manufacturers, err
}

// FindByID returns a manufacturer with given id or returns the error.
func (m *ManufacturerDAO) FindByID(id string) (Manufacturer, error) {
	m.Db.Connect()
	var manufacturer Manufacturer
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).FindId(bson.ObjectIdHex(id)).One(&manufacturer)
	return manufacturer, err
}

// FindByName returns a manufacturer with given name or returns the error.
func (m *ManufacturerDAO) FindByName(name string) (Manufacturer, error) {
	m.Db.Connect()
	var manufacturer Manufacturer
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).Find(bson.M{"name": name, "model": MANUFACTURERMODEL}).One(&manufacturer)
	return manufacturer, err
}

// Insert a manufacturer into database.
func (m *ManufacturerDAO) Insert(manufacturer Manufacturer) error {
	m.Db.Connect()
	manufacturer.Model = MANUFACTURERMODEL
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).Insert(&manufacturer)
	return err
}

// Upsert a manufacturer into database.
func (m *ManufacturerDAO) Upsert(manufacturer Manufacturer) (*mgo.ChangeInfo, error) {
	m.Db.Connect()
	manufacturer.Model = MANUFACTURERMODEL
	info, err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).Upsert(bson.M{"name": manufacturer.Name}, &manufacturer)
	return info, err
}

// Update an existing manufacturer.
func (m *ManufacturerDAO) Update(manufacturer Manufacturer) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).UpdateId(manufacturer.ID, &manufacturer)
	return err
}

// Delete an existing manufacturer.
func (m *ManufacturerDAO) Delete(manufacturer Manufacturer) error {
	m.Db.Connect()
	err := m.Db.MongoDb.C(MANUFACTURERCOLLECTION).Remove(&manufacturer)
	return err
}
