package dominando.android.data_room

import dominando.android.data.BooksRepository
import dominando.android.data.model.Book
import dominando.android.data.util.FileHelper
import dominando.android.data_room.database.AppDatabase
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
import java.lang.Exception
import java.util.*
import dominando.android.data_room.entity.Book as BookEntity

class RoomRepository(db: AppDatabase,
                     private val fileHelper: FileHelper) : BooksRepository {

    private val bookDao = db.bookDao()

    override fun saveBook(book: Book): Completable {
        if (book.id.isBlank()) {
            book.id = UUID.randomUUID().toString()
        }
        return bookDao.save(BookConverter.fromData(book))
    }

    override fun loadBooks(): Flowable<List<Book>> {
        return bookDao.bookByTitle()
                .flatMapIterable { it }
                .map { book ->
                    BookConverter.toData(book)
                }
                .toList()
                .toFlowable()
    }

    override fun loadBook(bookId: String): Maybe<Book> {
        return bookDao.bookById(bookId)
                .map { book -> BookConverter.toData(book) }
    }

    override fun remove(book: Book): Completable {
        return bookDao.delete(BookConverter.fromData(book))
                .andThen {
                    fileHelper.deletePreviousCoverExists(book)
                }
    }
}