package models

// Kofi represents a kofi
type Kofi struct {
	ID       int64  `xorm:"pk autoincr" json:"id" form:"id"`
	Name     string `xorm:"text" json:"name" form:"name"`
	Gemeinde string `xorm:"text" json:"gemeinde" form:"gemeinde"`
	KCoins   int64  `xorm:"bigint(11)" json:"kcoins"`
}

// Create creates a new kofi
func (k *Kofi) Create() (err error) {
	_, err = x.Insert(k)
	return
}

// Delete removes a kofi
func (k *Kofi) Delete() (err error) {
	_, err = x.Delete(k)
	return
}

// Update updates an existing kofi
func (k *Kofi) Update(moreCoins int64) (err error) {
	// Check if it exists
	exists, err := x.Where("id = ?", k.ID).Get(k)
	if err != nil {
		return err
	}
	if !exists {
		return ErrKofiDoesNotExist{ID: k.ID}
	}

	k.KCoins += moreCoins

	// Update
	_, err = x.Where("id = ?", k.ID).Update(k)
	return
}

// ReadAll returns all kofis
func (k *Kofi) ReadAll(orderby string) (interface{}, error) {
	var orderbyStmt = "k_coins DESC"
	if orderby == "name" {
		orderbyStmt = "name ASC"
	}
	kofis := []*Kofi{}
	err := x.OrderBy(orderbyStmt).Find(&kofis)
	return kofis, err
}
