import os,re,fdb,time
import logging
logging.basicConfig(level=logging.DEBUG)


def set_single_page_view (filepdfin):
    from pikepdf import Pdf, Dictionary, Name
    import os
    from pathlib import Path
    pdf=Pdf.open(filepdfin,allow_overwriting_input=True)
    # file_only_path=os.path.dirname(filepdfin)
    # file_without_ext = Path(filepdfin).stem
    pdf.Root.PageLayout=Name('/SinglePage')
    pdf.Root.PageMode=Name('/UseNone')
    pdf.save()


# Connect to the Firebird database
conn = fdb.connect(
    dsn=r'localhost:u:\medicus 3\data\medicus.fdb',  # Database path
    user='SYSDBA',  # Username
    password="masterkey",  # Password,
    charset="win1250")
# cur = conn.cursor()

cesta=r"u:\dropbox\ordinace\Dokumentace_ke_zpracování"

for file in os.listdir(cesta):
    if file.upper().endswith((".PDF")) and os.path.isfile(os.path.join(cesta,file)):
        pattern=r"(\d{9,10}) ((?:(?:19|20)\d\d)-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])) (\[.*)"
        nalezeno=re.search(pattern,file)
        if nalezeno:
            print(nalezeno.groups())
            x=nalezeno.groups()
            rodcis=nalezeno.group(1)
            datum=nalezeno.group(2)
            konec=nalezeno.group(5)
            print(datum)
            print(konec)
            print(rodcis,type(rodcis))
            cur = conn.cursor()
            cur.execute("select prijmeni, jmeno from kar where rodcis=?",(rodcis,))
            x = cur.fetchone()
            if x:
                if len(x[0].split(" "))==1:
                    prijmeni=x[0]
                else:
                    prijmeni=x[0].split(" ")[0]
                if len(x[1].split(" "))==1:
                    jmeno=x[1]
                else:
                    prijmeni=x[1].split(" ")[0]
                konecsouboru=file.split(rodcis)[1]
                novejmeno=rodcis+" "+datum+" "+prijmeni.strip()+", "+jmeno.strip()+" "+konec
                print(novejmeno)
                os.rename(os.path.join(cesta,file),os.path.join(cesta,novejmeno))
            cur.close()

