from typing import List

from DBConnection import postgresConnection
from Transaction import transaction
import psycopg2


def runScheduleWithLocking(db: postgresConnection, T: List[transaction]):
    for t in T:
        t.start()
    for t in T:  # has to be in a separate for loop
        t.join()

def runScheduleWithoutLocking(db: postgresConnection, T:List[transaction]):
    for t in T:
        t.start()
    for t in T:  # has to be in a separate for loop
        t.join()


if __name__ == '__main__':

    db = postgresConnection()
    db.reset_table()

    ######  TRANSACTIONS FOR THE SCHEDULE WITH LOCKING: BANK 1  #####

    t0 = transaction(0)
    t1 = transaction(1)
    t2 = transaction(2)
    t3 = transaction(3)
    t4 = transaction(4)
    t5 = transaction(5)
    t6 = transaction(6)
    t7 = transaction(7)
    t0.setAction(db.add_val_bank1, [5, 1], 0)  # 5
    t1.setAction(db.add_val_bank1, [100, 1], 1)  # 105
    t2.setAction(db.add_val_bank1, [200, 1], 2)  # 305
    t3.setAction(db.add_val_bank1, [150, 1], 3)  # 455
    t4.setAction(db.add_val_bank1, [50, 1], 4)  # 505
    t5.setAction(db.sub_val_bank1, [200, 1], 5)  # 305
    t6.setAction(db.sub_val_bank1, [5, 1], 6)  # 300
    t7.setAction(db.sub_val_bank1, [150, 1], 7)  # 150 <- SO THERE SHOULD BE 1150.- ON BANK 1

    T1 = [t0, t1, t2, t3, t4, t5, t6, t7]


    ######  TRANSACTIONS FOR THE SCHEDULE WITHOUT LOCKING: BANK 2 #####
    db.reset_table()

    g0 = transaction(1)
    g1 = transaction(2)
    g2 = transaction(3)
    g3 = transaction(4)
    g4 = transaction(5)
    g5 = transaction(6)
    g6 = transaction(7)
    g7 = transaction(8)
    g0.setAction(db.add_val_bank2, [5, 1])  # 5
    g1.setAction(db.add_val_bank2, [100, 1])  # 105
    g2.setAction(db.add_val_bank2, [200, 1])  # 305
    g3.setAction(db.add_val_bank2, [150, 1])  # 455
    g4.setAction(db.add_val_bank2, [50, 1])  # 505
    g5.setAction(db.sub_val_bank2, [200, 1])  # 305
    g6.setAction(db.sub_val_bank2, [5, 1])  # 300
    g7.setAction(db.sub_val_bank2, [150, 1])  # 150 <- SO THERE SHOULD BE 1150.- ON BANK 2

    T2 = [g0, g1, g2, g3, g4, g5, g6, g7]

    runScheduleWithLocking(db, T1)
    runScheduleWithoutLocking(db, T2)
