import os
import fdb
import csv,time,pandas as pd
import openpyxl


PathToSaveCSV=r"u:\NextCloudOrdinace\Reporty"
timestr = time.strftime("%Y-%m-%d %H-%M-%S ")
CSVname="Pacienti.xlsx"
# PathToSaveCSV=r"//tower/tempspeed"

con = fdb.connect(
    host='localhost', database=r'u:\MEDICUS 3\data\medicus.FDB',
    user='sysdba', password='masterkey',charset='WIN1250')

#Server=192.168.1.10
#Path=M:\Medicus\Data\Medicus.fdb

# Create a Cursor object that operates in the context of Connection con:
cur = con.cursor()

#rc hledaného pacienta
rc="495220197"

# import openpyxl module
import openpyxl
import xlwings as xw
wb = openpyxl.Workbook()
sheet = wb.active
# wb.save("sample.xlsx")

#Načtení očkování
cur.execute("select ockzaz.datum,latka from registr join kar on registr.idpac=kar.idpac join ockzaz on registr.idpac=ockzaz.idpac "
            "where rodcis=?",(rc,))
nacteno=cur.fetchall()
print(len(nacteno))

sheet.title="Očkování"
sheet.append(["Očkování"])
#nacteno jsou ockovani
for row in nacteno:
    row_datum=row[0].strftime('%d-%m-%Y') #date_obj.strftime('%Y-%m-%d')
    sheet.append((row_datum.strip()+chr(9)+row[1].strip(),))

sheet.column_dimensions['A'].width = 100  # Column A
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))


#RECEPTY
wb.create_sheet('Recepty',0)
sheet=wb['Recepty']

#Načtení receptů
cur.execute("""select 
recept.datum,recept.lek,recept.dop,recept.expori AS Poc,
CASE 
        WHEN recept.opakovani is null THEN 1
        ELSE recept.opakovani
    END AS OP,
recept.dsig,
recept.NOTIFIKACE_KONTAKT as notifikace
from recept LEFT Join RECEPT_EPODANI on recept.id_epodani=recept_epodani.id
LEFT join kar on recept.idpac=kar.idpac where rodcis=? and recept.lek is not null 
order by datum desc,erp desc """,(rc,))

nacteno=cur.fetchall()
print(len(nacteno))

sheet.title="Recepty"
sheet.append(["Recept"])
#nacteno jsou ockovani
for row in nacteno:
    row_datum=row[0].strftime('%d-%m-%Y')
    if row[2]:
        row_lek=row[1].strip()+" ("+row[2].strip()+")"
    else:
        row_lek = row[1].strip() + " ()"
    row_pocet=str(row[3]).strip()+"x"+chr(9)
    if row[4]:
        row_opakovani="op:"+str(row[4]).strip()+"x"+chr(9)
    else:
        row_opakovani = "op:1x"+chr(9)
    if row[5]:
        row_dsig=row[5].strip()+chr(9)
    else:
        row_dsig=""
    print(row_datum+row_lek+row_pocet+row_opakovani+row_dsig)

    sheet.append((row_datum,row_lek,row_pocet+row_opakovani+row_dsig,))

sheet.column_dimensions['A'].width = 12  # Column A
sheet.column_dimensions['B'].width = 50  # Column B
sheet.column_dimensions['C'].width = 50  # Column C
wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))

wb.save(os.path.join(PathToSaveCSV ,timestr+CSVname))


