# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import numpy as np
import pandas as pd

from IPython.display import display, Markdown
# -

# %load_ext autoreload
# %autoreload 2

import pymedphys.mosaiq

start = '2021-02-01 00:00:00'
end = '2021-03-01 00:00:00'

# +
centres = ['rccc', 'nbcc', 'sash']

servers = {
    'rccc': 'msqsql', 
    'nbcc': 'physics-server:31433',
    'sash': 'physics-server'
}

servers_list = [
    item for _, item in servers.items()
]

physics_location = {
    'rccc': 'Physics_Check',
    'nbcc': 'Physics',
    'sash': 'Physics_Check'
}

imrt_task_names = {
    'nbcc': ['Physics Check IMRT'],
    'rccc': ['IMRT Physics Check']
}

non_imrt_task_names = {
    'nbcc': ['Physics Check 3DCRT'],
    'rccc': ['3D Physics Check', 'Electron Factor']
}



sash_physics_task_name = 'Physics QA           '


# +
def get_staff_name(cursor, staff_id):
    data = pymedphys.mosaiq.execute(
        cursor,
        """
        SELECT
            Staff.Initials,
            Staff.User_Name,
            Staff.Type,
            Staff.Category,
            Staff.Last_Name,
            Staff.First_Name
        FROM Staff
        WHERE
            Staff.Staff_ID = %(staff_id)s
        """,
        {"staff_id": staff_id},
    )

    results = pd.DataFrame(
        data=data,
        columns=[
            "initials",
            "user_name",
            "type",
            "category",
            "last_name",
            "first_name",
        ],
    )

    return results


def get_qcls_by_date(cursor, location, start, end):
    data = pymedphys.mosaiq.execute(
        cursor,
        """
        SELECT
            Ident.IDA,
            Patient.Last_Name,
            Patient.First_Name,
            Chklist.Due_DtTm,
            Chklist.Act_DtTm,
            Chklist.Instructions,
            Chklist.Notes,
            QCLTask.Description
        FROM Chklist, Staff, QCLTask, Ident, Patient
        WHERE
            Chklist.Pat_ID1 = Ident.Pat_ID1 AND
            Patient.Pat_ID1 = Ident.Pat_ID1 AND
            QCLTask.TSK_ID = Chklist.TSK_ID AND
            Staff.Staff_ID = Chklist.Rsp_Staff_ID AND
            Staff.Last_Name = %(location)s AND
            Chklist.Act_DtTm >= %(start)s AND
            Chklist.Act_DtTm < %(end)s
        """,
        {"location": location, "start": start, "end": end},
    )

    results = pd.DataFrame(
        data=data,
        columns=[
            "patient_id",
            "last_name",
            "first_name",
            "due",
            "actual_completed_time",
            "instructions",
            "comment",
            "task",
        ],
    )

    results = results.sort_values(by=["actual_completed_time"])

    return results


# +
# with multi_mosaiq_connect(servers_list) as cursors:
#     for centre in centres:
#         display(Markdown('### {}'.format(centre)))
#         cursor = cursors[servers[centre]]
#         display(get_staff_name(cursor, physics_ids[centre]))

# +
# Working out physics_id

# with mosaiq_connect(servers['sash']) as cursor:
#     display(get_qcls_by_date(cursor, start, end))
    
# -

with pymedphys.mosaiq.connect(servers_list) as cursors:
    
    results = {
        centre: get_qcls_by_date(
            cursors[servers[centre]], physics_location[centre], start, end
        )
        for centre in centres
    }

for server in servers:
    results[server] = results[server].drop_duplicates(subset='actual_completed_time', keep='first')

for server in servers:
    display(Markdown("### {}".format(server)))
    
    display(results[server])


def count_results(results, imrt_task_names, non_imrt_task_names, server):
    
    imrt_results = 0
    non_imrt_results = 0
    
    for task in results[server]['task']:
        trimmed_task = task.strip()
        if trimmed_task in imrt_task_names[server]:
            imrt_results = imrt_results + 1
        elif trimmed_task in non_imrt_task_names[server]:
            non_imrt_results = non_imrt_results + 1
        else:
            print(trimmed_task)
    
    
    return {
        'imrt_results': imrt_results,
        'non_imrt_results': non_imrt_results
    }

# +
counts = {
    server: count_results(results, imrt_task_names, non_imrt_task_names, server)
    for server in ['rccc', 'nbcc']
}

counts
# -

# SASH results
len(results['sash']['task'])



StarcoderdataJupyterScriptsDedupFiltered