package models

// ListItems returns a list with all items, filtered by an optional searchstring
func ListItems(searchterm string) (items []Item, err error) {

	if searchterm == "" {
		err = x.Find(&items)
	} else {
		err = x.
			Where("title LIKE ?", "%"+searchterm+"%").
			Find(&items)
	}

	if err != nil {
		return []Item{}, err
	}

	// Range over all items and get their quantity.
	// Yes I know how inperformant this is. But we can't use a join here because of the way xorm handels the quantity property.
	for i, item := range items {
		items[i].Quantity, err = item.getQuantity()
		if err != nil {
			return []Item{}, err
		}
	}

	return items, nil
}
