import os,fdb,datetime

# 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()

def zapis_file(vstupconnection,idpac,cesta,souborname,prvnizavorka,soubordate,souborfiledate,poznamka):
    import funkce
    cur=vstupconnection.cursor()
    fileid = funkce.get_files_id(vstupconnection)
    with open(os.path.join(cesta,souborname), 'rb') as f:
        daticka = f.read()
    query = "insert into files (id,iduzi,iddoctyp,typ,idpac,filename,body,datum,datsouboru,poznamka) values(?,?,?,?,?,?,?,?,?,?)"
    cur.execute(query,(fileid,6,1,1,idpac,prvnizavorka+".pdf",daticka,soubordate,souborfiledate,poznamka[:99]))
    vstupconnection.commit()
    return fileid
def zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy,
                 datumsouboru):
    import funkce
    dekursid = funkce.get_dekurs_id(vstupconnection)
    cur = vstupconnection.cursor()
    print("Funkce zapis_dekurs hlasí OK")
    print("idpac", idpac)
    print("idodd", idodd)
    print("iduzi", iduzi)
    print("idfile", idfile)
    print("filename", filename)
    print("text", text)
    print("datumzpravy", datumzpravy)
    print("datumsouboru", datumsouboru)
    print("dekursid", dekursid)

#     rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
# {\stylesheet{\s0\fi0\li0\ql\ri0\sb0\sa0 Norm\'e1ln\'ed;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs32\f0\ul\fs20\cf1 Odkaz;}}
# \uc1\pard\s0\plain\cs20\f0\i\fs20 P\'f8\'edlohy: {\*\bkmkstart 0}\plain\cs32\f0\ul\fs20\cf1 BOOKMARKNAME{\*\bkmkend 0}\par
# \pard\s0\plain\cs15\f0\fs20 \par
# }
# """
    rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks "BOOKMARKNAME","Files:FILEID",9}}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
\uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par
\pard\s10{\*\bkmkstart 0}\plain\cs22\f0\ul\fs20\cf1 BOOKMARKNAME{\*\bkmkend 0}\par
\pard\s10\plain\cs15\f0\fs20 \par
}

    """
    # id idpac filename body docid typ datum iddoctyp poznamka idpac=2 iduzi=2 datsouboru id_edokument ext_id
    encodedbookmark = funkce.convert_to1250(filename)
    print("Encodedbookmark", encodedbookmark)
    rtf = rtf.replace("BOOKMARKNAME", encodedbookmark)
    rtf = rtf.replace("FILEID", str(idfile))
    rtf = rtf.replace("TEXTENTER", text)
    datumzapisu = datetime.datetime.now().date()
    caszapisu = datetime.datetime.now().time()
    print("Datumzapisu", datumzapisu)
    print("Caszapisu", caszapisu)
    print("RTF", rtf)
    cur.execute("insert into dekurs (id,idpac,idodd,iduzi,idprac,datum,cas,dekurs) values(?,?,?,?,?,?,?,?)",
                        (dekursid, idpac, idodd, iduzi, idprac, datumzapisu, caszapisu, rtf))
    vstupconnection.commit()


def convert_to1250(retezec):
    retezec=retezec.encode("cp1250")
    retezec=str(retezec)[2:]
    retezec = retezec[:-1]
    retezec=retezec.replace(r"\x",r"\'")
    return retezec


# x=convert_to1250("Příloha")
# print(x,len(x))

def get_dekurs_id(connection):
    try:
        query = "SELECT GEN_ID(Gen_Dekurs, 1) FROM RDB$DATABASE"
        cur = connection.cursor()
        cur.execute(query)
        newid=cur.fetchone()[0]
        print("Funkce GET_DEKURS_ID přiřadila nové ID:",newid)
        return(newid)
    except:
        print("Funkce GET_DEKURS_ID nepřiřadila nové ID")
        return(None)

def get_files_id(connection):
    try:
        query = "SELECT GEN_ID(Gen_Files, 1) FROM RDB$DATABASE"
        cur=connection.cursor()
        cur.execute(query)
        newid=cur.fetchone()[0]
        print(newid)
        return(newid)
    except:
        return(None)

def get_idpac(rodnecislo,connection):
    try:
        query = "SELECT idpac,prijmeni FROM kar where rodcis=?"
        cur = connection.cursor()
        cur.execute(query,(rodnecislo,))
        tmp_nacteno=cur.fetchone()
        tmp_id = tmp_nacteno[0]
        tmp_jmeno=tmp_nacteno[1]
        print(f"Pacient s rodným číslem {rodnecislo} má ID {tmp_id} a jméno {tmp_jmeno}")
        return (tmp_id)
    except:
        return(None)

