from ebookwords.adapter import db
from ebookwords.adapter import ebook_parser as parser
from ebookwords.adapter import ebook_extractor as extractor

from dataclasses import dataclass
import typing


@dataclass
class BookManager:
    db_client: db.DatabaseClient

    def store_ebook(self, file: typing.BinaryIO) -> None:
        ebook = parser.parse_epub(file)
        chapters = self._get_chapters(ebook)
        book = db.Book(ebook.title, chapters)
        self.db_client.add_book(book)

    @staticmethod
    def _get_chapters(ebook: parser.Ebook) -> typing.Iterator[db.Chapter]:
        for c in ebook.chapters:
            paragraphs = extractor.extract_paragraphs_from_html(c.html)
            yield db.Chapter(c.title, paragraphs)
