'''versionizer.py

Creates new version of a book
'''
import os
from bs4 import BeautifulSoup
from bookhelper import Book,  doi, utils
from . import BookAction


class VersionizeAction(BookAction):
    def validate(self):
        if not self.conf.no_doi:
            args = ["dc_symbol", "dc_password", "dc_prefix", "dc_identifier", ]
            for arg in args:
                if getattr(self.conf, arg, None) is None:
                    self.errors.append("Missing argument: %s" % arg)

            bookdoi = doi.BookDoi(self.conf)
            bookdoi.validate()
            if not bookdoi.errors:
                self.doi = bookdoi.doi
            self.errors += bookdoi.errors

        site = self.login()
        super().validate(site)

    def build_book(self, site):
        self.book = Book(site, self.conf.book, "live")

    def versionized_template(self):
        doi = getattr(self, 'doi', None)
        if doi:
            self.book.info['DOI'] = doi
        return utils.template_from_info(self.book.info)

    def versionized_bookpage_text(self):
        txt = self.book.book_page.text
        txt = (txt[:self.book.template_startpos] +
               self.versionized_template() +
               txt[self.book.template_endpos:])
        soup = BeautifulSoup(txt, 'html.parser')
        toc = soup.find('div', class_='BookTOC')
        content = toc.contents[0]
        stable_content = os.linesep
        for item in self.book.toc:
            stable_content += ("#"*item.depth) + item.stable_link + os.linesep

        content.replaceWith(stable_content)
        return soup.decode(formatter=None)

    def run(self):
        version_page_txt = self.versionized_bookpage_text()
        pagetitle = '%s/%s' % (self.book.book_page.title, self.conf.version)
        self.site = self.login()
        version_page = self.site.Pages[pagetitle]
        if version_page.text() and not self.conf.force_overwrite:
            self.errors.append("Page already exists")
        else:
            version_page.save(version_page_txt)

@@ -251,245 +251,8 @@
 oi:%0A
-            args = %5B%22dc_symbol%22, %22dc_password%22, %22dc_prefix%22, %22dc_identifier%22, %5D%0A            for arg in args:%0A                if getattr(self.conf, arg, None) is None:%0A                    self.errors.append(%22Missing argument: %25s%22 %25 arg)%0A%0A
     
@@ -292,16 +292,16 @@
 f.conf)%0A
+
         
@@ -393,28 +393,24 @@
 bookdoi.doi%0A
-    
         self
@@ -435,16 +435,58 @@
 .errors%0A
+        if self.errors:%0A            return
 %0A       

return on err