// Book.cpp
#include "Book.hpp"

#include <utility>              // std::move
#include <gdkmm/texture.h>      // pulls in the GTK bits only here
#include <iostream>

Book::Book(std::string_view idSha256,
           std::string_view title,
           std::string_view author,
           std::string_view filePath,
           std::string_view coverPath)
	: m_id(idSha256),
	  m_title(title),
	  m_author(author),
	  m_filePath(filePath),
	  m_coverPath(coverPath) {}

Book::Book() = default;
Book::Book(const Book&) = default;
Book::Book(Book&&) noexcept = default;
Book& Book::operator=(const Book&) = default;
Book& Book::operator=(Book&&) noexcept = default;
Book::~Book() = default;

bool Book::operator<(const Book& other) const noexcept {
	if (m_title != other.m_title)   return m_title  < other.m_title;
	if (m_author != other.m_author) return m_author < other.m_author;
	return m_id < other.m_id;
}

const Glib::RefPtr<Gdk::Texture>& Book::cover() const noexcept {
	return m_cover;
}

void Book::set_cover(const Glib::RefPtr<Gdk::Texture>& tex) {
	m_cover = tex;
}

void Book::set_cover(Glib::RefPtr<Gdk::Texture>&& tex) {
	m_cover = std::move(tex);
}

void Book::load_cover_from_disk() {
	// Skip if already loaded
	if (m_cover)
		return;

	// Try to load the cover from disk
	if (!m_coverPath.empty()) {
		// Check if file exists before attempting load
		if (!Glib::file_test(m_coverPath, Glib::FileTest::EXISTS)) {
			std::cerr << "Cover file missing: " << m_coverPath << std::endl;
			return;
		}

		try {
			auto tex = Gdk::Texture::create_from_filename(m_coverPath);
			if (tex) {
				m_cover = tex;
				return;
			}
		} catch (const Glib::Error& e) {
			std::cerr << "Failed to load cover from " << m_coverPath
					  << ": " << e.what() << std::endl;
		}
	}
}
