__author__ = 'Wendell Jones'

from tqdm import tqdm
from sqlalchemy import text
from sqlalchemy.orm import Session


class Dbexec():
    def __init__(self):
        pass

    def update_tvupdates(self, engine, available_updates, tablename):
        print('Creating update transaction.')

        # Build batch insert data
        updatelist = [
            {
                'seriesid': str(seriesid),
                'timestamp': available_updates[seriesid]
            }
            for seriesid in tqdm(
                available_updates,
                desc='Preparing tvupdates records',
                unit='record'
            )
        ]

        print('Applying updates to table.')
        # Use a transactional context; SQLAlchemy Connection.execute accepts
        # a list of parameter mappings for bulk inserts (it will use the DBAPI
        # executemany under the hood).
        with engine.begin() as conn:
            print(f'Truncating table {tablename} before insert.')
            conn.execute(text(f"TRUNCATE TABLE {tablename}"))
            print(f'Inserting {len(updatelist)} records into {tablename}.')
            if updatelist:
                conn.execute(
                    text(f"INSERT INTO {tablename} (seriesid, timestamp) VALUES (:seriesid, :timestamp)"),
                    updatelist,
                )
        print('Update of tvupdates table is complete.')

    def rawsql_select(self, engine, sqlquery, lprint):
        session = Session(engine)
        resultset = []
        rs = session.execute(text(sqlquery))
        for row in rs:
            resultset.append(row)
        session.close()
        return (resultset)

    def rawsql_insert(self, dbengine, sqlquery, lprint):
        session = Session(dbengine)
        try:
            session.execute(text(sqlquery))
        except Exception as e:
            print(str(e))
            lprint.logprint('error', 'Rollback for query: ' + sqlquery)
            session.rollback()
        else:
            session.commit()
            session.close()

    def __del__(self):
        pass


class SQLGenerate():

    def __init__(self):
        pass

    def read_updatetable(self, engine, lprint):
        seriessql = text('''
            SELECT seriesid, timestamp from updates.tvupdatedata;
            ''')
        Dbexec.execute_rawsql(self, engine, seriessql, lprint)

    def __del__(self):
        pass
