import logging

from sqlalchemy import create_engine, insert, update, select
from sqlalchemy.orm import Session, sessionmaker
from db.models import Base, Order, OrderStatus


def get_engine():
    return create_engine('postgresql+psycopg2://postgres:guardia123@192.168.1.204:5432/export-tray', echo=False)


def create_tables():
    engine = get_engine()

    Base.metadata.create_all(engine)

def drop_tables():
    engine = get_engine()

    tables = Base.metadata.tables
    logging.debug(tables)

    Session = sessionmaker(bind=engine)
    session = Session()

    for table in [Order, OrderStatus]:
        session.query(table).delete()

    session.commit()
    session.close()


    Base.metadata.drop_all(engine)
    
    
def insert_into_table(values_map, table_name):
    engine = get_engine()
    stmt = insert(table_name).values(values_map)

    with engine.connect() as conn:
        result = conn.execute(stmt)
        print(result)
        conn.commit()


def update_record(where_map, values_map, table_name):
    engine = get_engine()
    stmt = update(table_name).where(where_map).values(values_map)

    with engine.connect() as conn:
        result = conn.execute(stmt)
        print(result)
        conn.commit()

