import sqlalchemy
import progressbar
import psycopg2.errors

class Update():
    def __init__(self):
        global jprocess

    def rawexec(self, sqlquery):
        connection = engine.connect()
        try:    
            trans = connection.begin()
            connection.execute(str(sqlquery))
        except:
            trans.rollback()
        else:
            trans.commit()
            connection.close()
                
    def fileexec(self, sqlfile):
        connection = engine.connect()
        trans = connection.begin()
        for line in sqlfile:
            sqlquery = sqlquery + str(line)
        try:
            connection.execute(str(sqlquery))
        except:
            trans.rollback()
            lprint.logprint('error', 'Rollback for filename: ' + str(sqlfile))
            sqlfile.close()
            connection.close()
        else:
            trans.commit()
            sqlfile.close()
            connection.close()
        
    def ormexec(self, listing, tablename):
        try:
            ins = tablename.insert()
            result = engine.execute(ins, listing)
        except sqlalchemy.exc.IntegrityError as ie:
            if 'UNIQUE KEY' in ie.args[0]:
                return True
        except psycopg2.errors.UniqueViolation as ie2:
            if 'unique constraint' in ie.args[0]:
                return True
        else:
            return False        
        
    def __del__(self):
        pass

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

    def update_tables(engine, updatesapi, tablename):
        jprocess = loadjson()
        print('Now retrieving available updates.')
        print('Creating update transaction.')
        ins = tablename.insert()
        seriesupdates = jprocess.load(updatesapi)
        updatelist = []
        seriesrange = len(seriesupdates) 
        with progressbar.ProgressBar(maxval=seriesrange, redirect_stdout=True) as p:
            for key, value in seriesupdates.items():
                i = int(key)
                updater = {}
                updater['seriesid'] = key
                updater['timestamp'] = value
                updatelist.append(updater)
                if i <= seriesrange:
                    p.update(i)
                #time.sleep(0.1) 
        print('Update of tvupdates table is complete.')
        print('Done.')
        return(ins, updatelist)

    def __del__(self):
        pass
