package com.webtoonviewer.repository

import android.content.Context
import android.util.Log
import com.webtoonviewer.db.AppDatabase
import com.webtoonviewer.db.Book

class BookRepository(context: Context) {
    private val bookDao = AppDatabase.getDatabase(context).bookDao()

    suspend fun getAllBookTitles(): MutableList<String> {
        return bookDao.getAllTitles().toMutableList()
    }

    suspend fun getAllBooks(): MutableList<Book> {
        return bookDao.getAllBooks().toMutableList()
    }

    suspend fun getBookByTitle(title: String): Book? {
        return bookDao.getBookByTitle(title)
    }

    suspend fun getBookById(id: Int): Book? {
        return bookDao.getBookById(id)
    }

    suspend fun updateTitleById(id: Int, title: String) {
        bookDao.updateTitleById(id, title)
    }

    suspend fun updateInformationById(id: Int, info: BookInformation) {
        bookDao.updateInformationById(id, info.author, info.tag, info.description, info.thumbnail_name)
    }

    suspend fun updateDescriptionById(id: Int, description: String) {
        bookDao.updateDescriptionById(id, description)
    }

    suspend fun updateChaptersById(id: Int, chapters: List<String>, chapterSum: Int) {
        bookDao.updateChaptersById(id, chapters,chapterSum)
    }

    suspend fun updateBookmarkById(id: Int, bookmarkChapter: String, bookmarkPosition: Int, bookmarkTopOffset: Int) {
        bookDao.updateBookmarkById(id, bookmarkChapter, bookmarkPosition, bookmarkTopOffset)
    }

    suspend fun updateIsLocal(id: Int, isLocal: Int) {
        bookDao.updateIsLocalById(id, isLocal)
    }

    suspend fun addNewBook(book: Book) {
        bookDao.addBook(book)
    }

    suspend fun copyBook(sourceId: Int, targetId: Int) {
        val book = bookDao.getBookById(sourceId)
        if (book != null) {
            bookDao.updateTitleById(targetId, book.title)
            bookDao.updateInformationById(targetId, book.author, book.tag, book.description, book.img)
            bookDao.updateChaptersById(targetId, book.chapters, book.chapterSum)
            bookDao.updateBookmarkById(targetId, book.bookmarkChapter, book.bookmarkPosition, book.bookmarkTopOffset)
            bookDao.updateIsLocalById(targetId, book.isLocal)
        }
    }

    suspend fun deleteBookById(bookId: Int) {
        bookDao.deleteBookById(bookId)
    }

}