import json
from datetime import datetime
import os
import pyodbc
import random
import string

# Path to your Access database
db_path = r"u:\Dropbox\!!!Days\Downloads Z230\Access\Banka.accdb"
# Connection string
conn_str = (
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    rf"DBQ={db_path};"
)
# Connect to database
conn = pyodbc.connect(conn_str)

# Create cursor
cursor = conn.cursor()

cursor.execute("delete from transactions")
conn.commit()



# Load from file, načtení bankovních pohybů
with open(r"u:\Dropbox\!!!Days\Downloads Z230\Fio\pohyby.json", "r", encoding="utf-8") as f:
    transactions = json.load(f)
# print(transactions["accountStatement"]["transactionList"])
# Process
for tx in transactions["accountStatement"]["transactionList"]["transaction"]:
    #ID pohybu
    idpohybu=str(tx["column22"]["value"])
    datum=tx["column0"]["value"]

    #Datum transakce
    datum = datetime.strptime(datum, "%Y-%m-%d%z")
    datum = datum.date()

    #Částka
    objem = int(tx["column1"]["value"])

    #Měna
    mena = tx["column14"]["value"]

    #Název protiúčtu
    nazevprotiuctu=tx["column10"]["value"]

    #Typ transakce
    typ = tx["column8"]["value"]

    #Konstantní symbol
    if tx["column4"] is not None:
        kss=tx["column4"]["value"]
    else:
        kss=""

    # Provedl
    if tx["column9"] is not None:
        provedl = tx["column9"]["value"]
    else:
        provedl = ""

    # ID pokynu
    if tx["column17"] is not None:
        idpokynu = str(tx["column17"]["value"])
    else:
        idpokynu = ""


    # print (idpohybu,datum,objem,mena,nazevprotiuctu,typ,kss,provedl,idpokynu)
    # if idpohybu=="3016989040":
    #     # Uložení do Accessu, jestli ještě neexistuje")
    #     cursor.execute("insert into transactions (idpohybu, datum) values (?,?)", (idpohybu, datum))
    #     conn.commit()
    # print("committed")

    print (idpohybu,datum,objem,mena,nazevprotiuctu,typ,kss,provedl,idpokynu)
    print(type(idpohybu))
    # Uložení do Accessu, jestli ještě neexistuje")
    cursor.execute("insert into transactions (idpohybu, datum,objem,mena,nazevprotiuctu,ks,typ,provedl,idpokynu) values (?,?,?,?,?,?,?,?,?)",
                   (idpohybu, datum,objem, mena, nazevprotiuctu,kss,typ,provedl,idpokynu))
    # cursor.execute("insert into transactions (idpohybu) values (?)", (idpohybu))
    conn.commit()
    print("committed")