package models

// Community represents a community
type Community struct {
	ID     int64  `xorm:"pk autoincr" json:"id" form:"id"`
	Name   string `xorm:"text" json:"name" form:"name"`
	KCoins int64  `xorm:"bigint(11)" json:"kcoins"`

	KonfiCount int64   `xorm:"bigint(11)" json:"konfi_count" form:"konfis"`
	CoinsQuota float64 `xorm:"-" json:"coins_quota"`
}

// Create creates a new community
func (c *Community) Create() (err error) {
	_, err = x.Insert(c)
	return
}

// Delete removes a community
func (c *Community) Delete() (err error) {
	_, err = x.Delete(c)
	return
}

// ReadAll returns all communites
func (c *Community) ReadAll(orderby string) (interface{}, error) {

	orderbyStmt := "CoinsQuota DESC"
	if orderby == "name" {
		orderbyStmt = "Name ASC"
	}

	communities := []*Community{}
	err := x.Select("*, (cast(k_coins AS FLOAT) / cast(konfi_count AS FLOAT)) as CoinsQuota").
		OrderBy(orderbyStmt).
		Find(&communities)
	if err != nil {
		return nil, err
	}

	for i, c := range communities {
		if c.KCoins == 0 {
			continue // Would otherwise divide by zero
		}
		communities[i].CoinsQuota = float64(c.KCoins) / float64(c.KonfiCount)
	}

	return communities, nil
}

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

	c.KCoins += moreCoins

	// Update
	_, err = x.
		Cols("k_coins").
		Where("id = ?", c.ID).
		Update(c)
	if err != nil {
		return
	}

	c.CoinsQuota = float64(c.KCoins) / float64(c.KonfiCount)

	return
}
