import kutil
import klammer_base

NUMBER_VAR = "___NUM___"

class Section(klammer_base.Klammer_base):
    label_number = 0
    count = 7
    indices = [0] * count
    def __init__(self, K, level, numbered=True):
        super().__init__(K)
        # Add front and back matter elements as special cases:
        if level == "preface":
            self.preface = True
            self.level = 0
            self.title = None
        else:
            self.preface = False
            self.level = level
        self.numbered = numbered
        self.part = 1

    def html(self):
        tags = "kt-part kt-chapter h1 h2 h3 h4 h5 h6 h7".split()
        display_names = "Part Chapter".split()
        id = f' id="{self.id}"' if self.id else ""
        # number_class = " numbered" if self.numbered else ""
        number_class = "" # The variable is sufficient?
        title = self.title
        tag = tags[self.level]
        if self.numbered:
            """
            Section.indices[self.level] += 1
            for i in range(self.level + 1, Section.count):
                Section.indices[i] = 0
            level_number = ".".join([str(e) for e in Section.indices])
            title = f'<span class="sectionnumber">{level_number}</span> {title}'
            """
            title = f'<span class="sectionnumber">{NUMBER_VAR}</span> {self.title if self.title else ""}'
        if self.level < 1:  # < 2 for "Chapter"
            #title = f"{tag} {Section.indices[self.level]} {title}"
            title = f"{display_names[self.level]} {title if title else ''}"

        result = f'<{tag}{id}{number_class}>{title}</{tag}>\n\n'
        return result

    def tex(self):
        # names = "part chapter section subsection subsubsection paragraph subparagraph subsubparagraph subsubsubparagraph".split()
        names = "part sA sB sC sD sE".split()

        #self.show()
        if self.id:
            id = self.id
        else:
            id = f"-s{Section.label_number}"
            Section.label_number += 1

        result = ''
        if self.__dict__.get("n") and self.n:
            result += f'\\setcounter{{chapter}}{{{int(self.n)-1}}}\n'
        #if self.id:
        #    result += 
        #if self.level == 1:
            #result += '\\newpage\n\n'
        #    result += '\\vspace*{24pt}'
        suffix = "" if self.numbered else "*"
        result += f'\\{names[self.level]}{suffix}{{{self.title}}}'
        result += f'\n\\hypertarget{{{id}}}{{}}'

        # result = kutil.protect_klammertext_special_characters(result)

        result = f"%__sectionlink__{id}__{self.title}__" + "\n" + result
        return result

# Need to implement the procedural numbering for the txt target
#    def txt(self):
#        return self.title
