import datetime
import time

from sqlalchemy.ext.automap import automap_base
# from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

from download import getPatient
from models import *

MAX_EXE_TIME = 3600 # 1 hour
rescan = False

session = Session()

Base = automap_base()
engine = create_engine('mysql+pymysql://ntuh:n122119493@virtualmin.ntuh.net/ck', pool_recycle=3600)
Base.prepare(engine, reflect=True)
SessionCK = sessionmaker(bind=engine)

session_ck = SessionCK()

start_time = time.time()
CKPatient = Base.classes.ck_patient
for p in session_ck.query(CKPatient):
    print(p.id, p.medical_records)
    p2 = session.query(Patient).get(p.medical_records)
    if p2 is None:
        # print(p.id, p.medical_records)
        if rescan == True:
            getPatient(p.medical_records, rescanStudy = rescan)
        # exit()
    else:
        if rescan == False:
            getPatient(p.medical_records, rescanStudy = rescan)
        # print('skipped', p2.patient_id, p2.counter, p2.saved)

    diff_time = time.time() - start_time
    str_time = str(datetime.timedelta(seconds=diff_time))
    print(f'Exec time {str_time}')    
    if diff_time > MAX_EXE_TIME:
        break

