package models

// Book holds a book
type Book struct {
	ID          int64   `xorm:"int(11) autoincr not null unique pk" json:"id"`
	Title       string  `xorm:"varchar(250) not null" json:"title"`
	Description string  `xorm:"varchar(750)" json:"description"`
	Isbn        string  `xorm:"varchar(30)" json:"isbn"`
	Year        int64   `xorm:"int(11)" json:"year"`
	Price       float64 `xorm:"double" json:"price"`
	Status      int64   `xorm:"int(11)" json:"status"`
	PublisherID int64   `xorm:"int(11)" json:"publisherID"`
	Created     int64   `xorm:"created" json:"created"`
	Updated     int64   `xorm:"updated" json:"updated"`

	Quantity  int64     `xorm:"-" json:"quantity"`
	Publisher Publisher `xorm:"-" json:"publisher"`
	Authors   []Author  `xorm:"-" json:"authors"`
}

// TableName returns the name for the books table
func (Book) TableName() string {
	return "books"
}

// GetBookByID gets a Book by its ID
func GetBookByID(ID int64) (book Book, exists bool, err error) {
	// Get the Book
	has, err := x.ID(ID).Get(&book)

	if has {
		// Get the books quantity. We can't join it because xorm ignores the Quantity option in struct
		book.Quantity, err = book.getQuantity()
		if err != nil {
			return Book{}, false, err
		}

		// Get publisher. We can't join it because xorm ignores the PublisherID option in struct
		book.Publisher, _, err = GetPublisherByID(book.PublisherID)
		if err != nil {
			return Book{}, false, err
		}

		// Get all authors
		book.Authors, err = GetAuthorsByBook(book)
		if err != nil {
			return Book{}, false, err
		}
	}

	return book, has, err
}
