import os
import csv
import glob
import quopri
import re


fmask = "*.pdf"
f = sorted(glob.glob(fmask))
CSVPath = "Title.csv"
TemplatePath = 'template.html'
OutPath = 'output.html'

if not os.path.exists(TemplatePath):
    TemplatePath = "Title-source.html"
    OutPath = "Title.html"
if not os.path.exists(TemplatePath):
    TemplatePath = "/doc4.eBook2.etc2/Title-source.html"
    OutPath = "Title.html"

DirName = os.getcwd()


def usage():
    print("usage: python MakeTitleHTML.py [create|html|imagehtml]")

def create_source_csv():
    CSVPath = "Title-source.csv"
    with open(CSVPath, "w", newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        for fn in f:
            fn_base = os.path.splitext(fn)[0]
            idx = ''
            if ' ' in fn_base:
                parts = fn_base.rsplit(' ', 1)
                if parts[1].isdigit():
                    idx = parts[1]
                    fn_base = parts[0]
            writer.writerow([fn_base, fn, idx])

def make_html():
    db = {}
    key = []
    BaseDirectory = ''
    PageOffset = 0
    iPrint = 0
    c = 0

    with open(CSVPath, "r", encoding = 'cp932') as csvfile:
#    with open(CSVPath, "r", encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)

        prev = []
        for row in reader:
            if not row: continue

            print("row: ", row)
            _aa = row
            na = len(_aa)
            title = _aa[0] if na >= 1 else None
            file  = _aa[1] if na >= 2 else None
            index = _aa[2] if na >= 3 else None
            page  = _aa[3] if na >= 4 else None
            if title.startswith('#!'):
                key_cmd = title[2:]
                if key_cmd.lower() == 'end':
                    break
                elif key_cmd.lower() == 'basedirectory':
                    BaseDirectory = file
                elif key_cmd.lower() == 'pageoffset':
                    PageOffset = int(file)
                elif key_cmd.lower() == 'print':
                    file = file.replace('\\n', '\n').replace('\\t', '\t')
                    db[f"#!Print_{iPrint}"] = file
                    key.append(f"#!Print_{iPrint}")
                    iPrint += 1
                prev = []
                continue

            if title is None: continue
            if file is None: file = prev[1]
            if index is None: index = prev[2]

            if title not in db: key.append(title)
            if index is None: index = 'no index'

            file_path = os.path.join(BaseDirectory, file) if BaseDirectory else file
            try:
                page = int(page) + PageOffset
            except:
                pass

            opt = f"#page__equal__{page}" if page else ''

            if title in db:
                db[title] += f" (<a href=\"{file_path}{opt}\" target=\"_blank\">{index}</a>)"
            else:
                db[title] = f"<a href=\"{file_path}{opt}\" target=\"_blank\">{title}</a> (<a href=\"{file_path}{opt}\" target=\"_blank\">{index}</a>)"
            prev = row
            c += 1

    with open(TemplatePath, "r", encoding='cp932') as template_file:
#    with open(TemplatePath, "r", encoding='utf-8') as template_file:
        content = template_file.read()
#    content = Utils.QPEncode(content)
    content = quopri.encodestring(content.encode('cp932'))

    OtherLinks = ''
    for i, key in enumerate(key):
        k = key
        v = db[key]
#        k = Utils.QPEncode(k)
        k = quopri.encodestring(k.encode('cp932'))
        k = re.escape(k)
        if re.search(k, content, re.IGNORECASE):
            content = re.sub(k, v, content, flags=re.IGNORECASE)
        else:
            OtherLinks += f"{v}<br>\n"

    '''
#    dl = Utils.QPEncode('{DirName}')
    dl = quopri.encodestring('{DirName}'.encode('cp932'))
    content = re.sub(dl, DirName, content, flags=re.IGNORECASE)
#    ol = Utils.QPEncode('{OtherLinks}')
    ol = quopri.encodestring('{OtherLinks}'.encode('cp932'))
    content = re.sub(ol, OtherLinks, content, flags=re.IGNORECASE)
    '''

#    content = Utils.QPDecode(content)
    content = quopri.decodestring(content)
    content = content.decode('cp932').replace('__equal__', '=')

    with open(OutPath, "w", encoding='cp932') as out_file:
#    with open(OutPath, "w", encoding='utf-8') as out_file:
        out_file.write("<H1>Sorted by title</H1>\n")
        out_file.write(content)
        out_file.write("<hr>\n")
        out_file.write("<H1>Sorted by volume</H1>\n")

    with open(CSVPath, "r", encoding='cp932') as csvfile:
#    with open(CSVPath, "r", encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        currentfile = ''
        prev = []
        for row in reader:
            if not row:
                continue
            if row[0].startswith('#!End'):
                break
            if row[0].startswith('#!'):
                continue

            _aa = row
            na = len(_aa)
            title = _aa[0] if na >= 1 else None
            file  = _aa[1] if na >= 2 else None
            index = _aa[2] if na >= 3 else None
            page  = _aa[3] if na >= 4 else None
 
            if title is None: continue
            if file is None: file = prev[1]
            if index is None: index = prev[2]

            if currentfile != file:
                with open(OutPath, "a", encoding='cp932') as out_file:
#                with open(OutPath, "a", encoding='utf-8') as out_file:
                    out_file.write("<hr>\n")
                    out_file.write(f"<H2>{file}</H2>\n")
                currentfile = file

            db[title] = db[title].replace('__equal__', '=')
            with open(OutPath, "a", encoding='cp932') as out_file:
#            with open(OutPath, "a", encoding='utf-8') as out_file:
                out_file.write(f"{db[title]}<br>\n")
            prev = row


if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        usage()
        sys.exit()

    command = sys.argv[1]
    if command == 'create':
        create_source_csv()
    elif command == 'html':
        make_html()
    else:
        usage()
