package models

import "fmt"

// BookPublisher struct to join books with publishers
type BookPublisher struct {
	Book      `xorm:"extends"`
	Publisher `xorm:"extends"`
}

// ListBooks returns a list with all books, filtered by an optional searchstring
func ListBooks(searchterm string) (books []*Book, err error) {

	if searchterm == "" {
		err = x.Table("books").
			//Join("INNER", "publishers", "books.publisher = publishers.id").
			Find(&books)
		if err != nil {
			fmt.Println("Error getting Books", err)
		}
	} else {
		err = x.Where("title LIKE ?", "%"+searchterm+"%").Find(&books)
		if err != nil {
			fmt.Println("Error getting Books", err)
		}
	}

	// Get all authors, publishers and quantities
	for i, book := range books {

		// Get quantities
		books[i].Quantity, err = GetQuantityByBook(book.ID)
		if err != nil {
			fmt.Println("Error getting quantity:", err)
		}

		// Get publisher
		books[i].PublisherFull, _, err = GetPublisherByID(book.Publisher)
		if err != nil {
			fmt.Println("Error getting publisher:", err)
		}

		// Get all authors
		books[i].Authors, err = GetAuthorsByBook(book.ID)
		if err != nil {
			fmt.Println("Error getting authors:", err)
		}
	}

	return books, err
}
