"""
Pattern verification script
Verifies the spacing in a patt using bsa TMITPIDHST
Verifies the beam is present using bsa TMITHST

Functions are not well generalized, mainly meant to break up the script into
digestable parts

Author: Ryan McClanahan (rpm)
"""

from epics import caget, caput, camonitor, camonitor_clear
from edef import BSABuffer
import os
import ScPatternSelect
import checks.check_bpm
import checks.check_rm
import time
import config
import argparse
import datetime
import socket
from re import split as re_split
import json
import argparse
from tools.epics_script_controls import EpicsControls
import math
import numpy as np
import tools.helpers
import enum


parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="patt verification for {IOC}, on {SYS}, with {UNIT}",
)
parser.add_argument(
    "--SYS",
    default="SYS0",
    help="macro like argument for the patt server, eg SYS0, B015...",
)
parser.add_argument(
    "--UNIT",
    default="1",
    help="macro like argument for the patt server, eg 1,2,3...",
)
parser.add_argument(
    "--IOC",
    default="sioc-sys0-ts01",
    help="macro like argument for the patt server, eg sioc-sys0-ts01, sioc-b015-ts01",
)
parser.add_argument(
    "--ENABLE",
    action="store_true",
    help="Enables invasive testing, e.g. testing tpg beam classes",
)
parser.add_argument(
    "--RECURSIVE",
    action="store_true",
    help="Enables recursive testing of all patterns in the test directory",
)
parser.add_argument(
    "--DEV_MODE",
    action="store_true",
    help="Dev mode for testing the script on dev with its quirks",
)
parser.add_argument(
    "--HOLD_BUFFS",
    action="store_true",
    help="BSA buffers do not get released",
)
parser.add_argument(
    "--KEEP_RUNNING",
    action="store_true",
    help="just keep running, just keep running, just keep running...",
)
parser.add_argument("--bsa_timeout", default=60, help="timeout for bsa buffers")
args = parser.parse_args()

patt_sel = ScPatternSelect.ScPatternSelect(args.SYS, args.UNIT, args.IOC)

epics_ctrls = EpicsControls(
    f"TPG:{args.SYS}:{args.UNIT}:PATT_VERIFY",
    terminalMessages=True,
    pvMessages=True,
    heartbeat=True,
)

DEST_NUMS = [0, 1, 2, 3, 4]
DISABLE = 0
EXCLUSION = 1
INCLUSION = 2

FIXED_RATE = 0
AC_RATE = 1
EXP_SEQ = 2

DEST_UNCHECKED = 0
DEST_CHECKED = 1

TIME_SLOTS = [1, 2, 3, 4, 5, 6]

TPG_BASE_PV = patt_sel.globals.get_tpg_base_pv()

# TODO: make error code enum

# Checks configuration
CHECKS = {
    "rate_measures": None,
    "bsa_buff_complete": None,
    "has_good_tmit": None,
    "all_bsss_pid_in_bsa": None,
    "bsss_tmit_match_bsa_on_pid": None,
}


def getReportDir(run_date):
    """
    Get the directory with all of the test pattern reports/info files, etc.
    """
    return os.path.join(patt_sel.globals.get_report_top(), run_date)


def getInfoFile(run_date):
    """
    Get the full path to the info file
    """
    return os.path.join(getReportDir(run_date), "test_info.txt")


def getReportFile(run_date):
    """"""
    return os.path.join(getReportDir(run_date), "patt_verify_report.json")


def makeFile(fname):
    """
    Makes the file if it does not exist
    """
    if not os.path.exists(fname):
        with open(fname, "w") as open_file:
            pass


def getDataFile(pattName, run_date, run_time):
    data_file_tail = pattName + "_" + run_time + ".json"
    data_file = os.path.join(getReportDir(run_date), data_file_tail)

    return data_file


def initInfoFile(run_date):
    """
    Check if info file exists.
    Does not exist: write a header
    Does exist: pass
    """
    if not os.path.exists(getInfoFile(run_date)):
        with open(getInfoFile(run_date), "w") as info_file:
            info_file.write(
                f"---Pattern Verification Human Readable INFO for {run_date}---"
            )
            info_file.write("\ngenerated by verify_patter.py in TpgScripts\n")


def initTestPattReport(test_patt_name, run_date, run_time):
    """ """
    test_patt_report = {}
    test_patt_report["Name"] = test_patt_name
    test_patt_report["Checks"] = CHECKS
    test_patt_report["run_time"] = run_time
    test_patt_report["run_date"] = run_date
    test_patt_report["exit_message"] = None
    return test_patt_report


def getMetaData(test_patt_name):
    """
    get the throughputs, pid_spacings, and slow_dest_trigs
    """
    epics_ctrls.break_point("Collecting pattern data from the meta.json")
    try:
        throughputs = patt_sel.get_throughputs(test_patt_name)
        for dest, tp in throughputs.items():
            throughputs[dest] = round(tp / 0.98)
    except:
        throughputs = None
    print(f"---{throughputs}---")

    try:
        pid_spacings = patt_sel.get_pid_spacings(test_patt_name)
    except:
        pid_spacings = {}

    try:
        slow_dest_trigs = patt_sel.get_slow_dest_trigger_rates(test_patt_name)
    except:
        slow_dest_trigs = None

    return throughputs, pid_spacings, slow_dest_trigs


def organizePattData(
    patt_data, throughputs: dict, pid_spacings: dict, slow_dest_trigs: dict
) -> dict:
    """
    I wanted to make the structure of this a lot easier to follow and access
    Takes in a patt_data from the sc timing patts NTTable and formats it
    into a dictionary named patt_data_org
    see the following example:

    patt_data['PATTERN_NAME'] = SC_DIAG0_STD_AC_30_Hz_off_3_SC_BSYD_STD_FR_102_Hz_SC_SXR_EXP_FR_1.0_kHz_off_7

    patt_data_org['Data'] = {
                    0: {'Name': 'LASER', 'Rate': 0, 'Active': False, 'Timing Source': 'FR'},
                    1: {'Name': 'SC_DIAG0', 'Rate': 30.0, 'Active': True, 'Timing Source': 'AC'},
                    2: {'Name': 'SC_BSYD', 'Rate': 102.0, 'Active': True, 'Timing Source': 'FR'},
                    3: {'Name': 'SC_HXR', 'Rate': 0, 'Active': False, 'Timing Source': 'FR'},
                    4: {'Name': 'SC_SXR', 'Rate': 1000.0, 'Active': True, 'Timing Source': 'FR'}
    }
    """
    epics_ctrls.break_point("Organizing pattern data")
    patt_data_org = {}
    patt_data_org["PATTERN_NAME"] = patt_data["PATTERN_NAME"]
    patt_data_org["Data"] = {}
    for dest_num in DEST_NUMS:

        patt_data_org["Data"][dest_num] = {}

        patt_data_org["Data"][dest_num]["Name"] = patt_sel.globals.DEST_NAMES[dest_num]

        patt_data_org["Data"][dest_num]["Rate"] = patt_data[
            f"{patt_sel.globals.DEST_NAMES[dest_num]}_RATE_Hz"
        ]

        patt_time_src = patt_data[
            f"{patt_sel.globals.DEST_NAMES[dest_num]}_TIMING_SOURCE"
        ]

        if patt_time_src != "None":
            patt_data_org["Data"][dest_num]["Active"] = True
        else:
            patt_data_org["Data"][dest_num]["Active"] = False

        if patt_data[
            f"{patt_sel.globals.DEST_NAMES[dest_num]}_TIMING_SOURCE"
        ].__contains__("AC"):
            patt_data_org["Data"][dest_num]["Timing Source"] = "AC"
        else:
            patt_data_org["Data"][dest_num]["Timing Source"] = "FR"

        patt_data_org = addPattData(
            patt_data_org, dest_num, throughputs, "throughput", None
        )

        patt_data_org = addPattData(
            patt_data_org, dest_num, pid_spacings, "pid_spacings", None
        )

        patt_data_org = addPattData(
            patt_data_org, dest_num, slow_dest_trigs, "slow_dest_trigs", None
        )

    return patt_data_org


def addPattData(patt_data: dict, dest_num: int, new_data: dict, new_key, default):
    """ """
    if new_data is None:
        patt_data["Data"][dest_num][new_key] = default
        return patt_data
    if dest_num in new_data.keys():
        patt_data["Data"][dest_num][new_key] = new_data[dest_num]
    else:
        patt_data["Data"][dest_num][new_key] = default
    return patt_data


def bsaBuffDestInit(bsa_buff, inclusion, dest_num):
    """
    Need to write to pvs to configure the bsa buffer
    """
    # reset all destination masks
    for index in range(1, 5):
        caput(
            f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:DST{index}", DEST_UNCHECKED
        )

    # write to destination mode pv, want inclusion
    caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:DESTMODE", inclusion)

    # write to all aplicable dest mask pvs
    caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:DST{dest_num}", DEST_CHECKED)


def bsaBuffAcInit(bsa_buff):
    """
    Extra initialization for AC buffers
    Set time slot to TS4 and rate to 60Hz
    """
    caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:RATEMODE", 1)
    caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:ACRATE", "60Hz")
    if args.DEV_MODE:
        caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:ACRATE", "1Hz")

    for time_slot in TIME_SLOTS:
        if time_slot != 4 and time_slot != 1:
            caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:TS{time_slot}", 0)
        else:
            caput(f"BSA:{args.SYS}:{args.UNIT}:{bsa_buff.number}:TS{time_slot}", 1)


def runAcBuffer(dest_num, n_measurements):
    """
    input
    --------
    strin representation of destination number
    Runs an AC buffer based on the dest_num

    output
    --------
    AC Rate BSA Buffer
    """
    epics_ctrls.break_point(f"initializing AC buffer for dest{dest_num}")
    ac_buffer = BSABuffer(f"ACpattVerify dest{dest_num}", user="timing team")
    bsaBuffDestInit(ac_buffer, getDestMode(), dest_num)
    bsaBuffAcInit(ac_buffer)
    ac_buffer.n_measurements = n_measurements
    return ac_buffer


def runFrBuffer(dest_num, n_measurements):
    """
    input
    --------
    strin representation of destination number
    Runs an FR buffer based on the dest_num

    output
    --------
    Fixed Rate BSA Buffer
    """
    epics_ctrls.break_point(f"initializing FR buffer for dest{dest_num}")
    fr_buffer = BSABuffer(f"FRpattVerify dest{dest_num}", user="timing team")
    bsaBuffDestInit(fr_buffer, getDestMode(), dest_num)
    if args.DEV_MODE:
        caput(f"BSA:{args.SYS}:{args.UNIT}:{fr_buffer.number}:RATEMODE", 0)
        caput(f"BSA:{args.SYS}:{args.UNIT}:{fr_buffer.number}:FIXEDRATE", "1Hz")
    fr_buffer.n_measurements = n_measurements
    return fr_buffer


def getDestMode() -> int:
    """
    Get the integer reperesentation of dest mode based on args.DEV_MODE
    output
    -------
    dest_mode:
        2: inclusion for normal script operations
        0: disable for testing when beam rate is not available
    """
    dest_mode = INCLUSION
    if args.DEV_MODE:
        dest_mode = DISABLE
    return dest_mode


def configureBuffers(patt_data):
    """
    Configure and run bsa buffers for each active dest
    Buffers are stored in patt_data["Data"][dest_num]["Buffer"]
    """
    dest_buff_map = {}
    for dest_num in patt_data["Data"]:
        # use throughput instead of rate if tp is defined
        if patt_data["Data"][dest_num]["throughput"] is not None:
            meascnt = int(patt_data["Data"][dest_num]["throughput"])
        else:
            meascnt = int(patt_data["Data"][dest_num]["Rate"])
        meascnt = meascnt * 5  # run for 5 sec if possible
        if meascnt > 20000:  # cap data points at 20000
            meascnt = 20000

        if args.DEV_MODE:
            meascnt = 5

        if not patt_data["Data"][dest_num]["Active"]:
            continue

        if patt_data["Data"][dest_num]["Timing Source"] == "AC":
            patt_data["Data"][dest_num]["Buffer"] = runAcBuffer(dest_num, meascnt)

        elif patt_data["Data"][dest_num]["Timing Source"] == "FR":
            patt_data["Data"][dest_num]["Buffer"] = runFrBuffer(dest_num, meascnt)

        dest_buff_map[dest_num] = patt_data["Data"][dest_num]["Buffer"].number

    return dest_buff_map


def initCheckBpms(dest_buff_map: dict, epics_ctrls: EpicsControls):
    """
    initializes the check_bpms object of type CheckBpm
    """

    host = socket.gethostbyaddr(socket.gethostname())[0]
    epics_ctrls.break_point(f"*****Init BPMs for host: {host}")

    if host.__contains__("lcls-dev3"):
        check_bpms = checks.check_bpm.CheckBpm(
            config.BPM_CONFIG_DEV, dest_buff_map, epics_ctrls
        )
    else:
        check_bpms = checks.check_bpm.CheckBpm(
            config.BPM_CONFIG, dest_buff_map, epics_ctrls
        )

    return check_bpms


def initRms(throughputs, test_patt_data):
    """
    initialize the rate measures (rms)
    """
    epics_ctrls.break_point("Configuring rate measures")

    rm_dest_time_sources = {}
    rm_dest_rates = {}
    slow_dest_reduced = (
        []
    )  # list of dests who expect a reduced rate on the slow dest triggers
    dest_throughputs = tools.helpers.toStrDests(throughputs, patt_sel)
    for dest in config.RM_DESTS:
        rm_dest_time_sources[dest] = test_patt_data[f"{dest}_TIMING_SOURCE"]
        if dest_throughputs is not None:
            if dest in dest_throughputs:
                rm_dest_rates[dest] = dest_throughputs[dest]
                if dest_throughputs[dest] != test_patt_data[f"{dest}_RATE_Hz"]:
                    slow_dest_reduced.append(dest)
            else:
                rm_dest_rates[dest] = test_patt_data[f"{dest}_RATE_Hz"]

        else:
            rm_dest_rates[dest] = test_patt_data[f"{dest}_RATE_Hz"]

    epics_ctrls.break_point(rm_dest_time_sources)

    check_rms = checks.check_rm.init_rms(rm_dest_time_sources, args.SYS, args.UNIT)

    return check_rms, rm_dest_rates, rm_dest_time_sources, slow_dest_reduced


def checkRms(
    test_patt_report,
    slow_dest_trigs,
    check_rms,
    rm_dest_rates,
    rm_dest_time_sources,
    slow_dest_reduced,
):
    """
    Check that the rate measures have their expected rates
    """
    ctrl_rates = tools.helpers.toStrDests(slow_dest_trigs, patt_sel)

    print(test_patt_report)
    print(slow_dest_trigs)
    print(rm_dest_rates)
    print(rm_dest_time_sources)
    print(slow_dest_reduced)

    # Check the Rate Measures, these should finish before the bsa
    test_patt_report["Checks"]["rate_measures"], rm_info = checks.check_rm.check_all(
        check_rms, rm_dest_rates, rm_dest_time_sources, ctrl_rates, slow_dest_reduced
    )

    epics_ctrls.break_point(
        f'rate measure check passed: {test_patt_report["Checks"]["rate_measures"]}'
    )

    return rm_info


def waitForBsaData(patt_data) -> bool:
    """
    Wait for all bsa aquisitions in patt_data to be ready
    -------
    output
    -------
    bsa_ready: (bool)
        True: bsa data is ready.
        False:  bsa data is not ready, the aquisitions timedout.
    """
    bsa_ready = False

    buffer_start = time.time()

    # Check each aquisition if it is ready, sleep for one second if not all aquisitions are ready
    # Don't need too wait for each to be ready, possible improvement in future if need speed
    while bsa_ready == False:
        time.sleep(1)
        bsa_ready = True

        # If the buffer takes too long to complete assume the data is bad
        time_elapsed = time.time() - buffer_start
        epics_ctrls.break_point(
            f"Waiting for bsa aquisitions to complete {int(time_elapsed)} of {args.bsa_timeout} seconds"
        )
        if time_elapsed >= int(args.bsa_timeout):
            bsa_ready = False
            break

        for dest_num in patt_data["Data"]:
            if patt_data["Data"][dest_num]["Active"]:
                # If any buffer is not ready skip to the next itteration of the while loop
                if (
                    caget(
                        f'BSA:{args.SYS}:{patt_data["Data"][dest_num]["Buffer"].number}:HST_READY'
                    )
                    == 0
                ):
                    bsa_ready = False
                    break
    epics_ctrls.break_point("All BSA buffers complete")
    return bsa_ready


def releaseBuffers(patt_data):
    """
    Release the bsa buffers in use and delete the references to them
    """
    if not args.DEV_MODE or not args.HOLD_BUFFS:
        epics_ctrls.break_point("releasing buffers")
        for dest_num in patt_data["Data"]:
            if patt_data["Data"][dest_num]["Active"]:
                patt_data["Data"][dest_num]["Buffer"].release()
    # still want to delete the buffers so the data can be saved
    for dest_num in patt_data["Data"]:
        if patt_data["Data"][dest_num]["Active"]:
            del patt_data["Data"][dest_num]["Buffer"]


def getInfo(run_date, run_time, patt_name, check_bpms, rm_info):
    """
    get a string representation of
    """
    info = f"\n****************************"
    info = info + f"\nPattern Name: {patt_name}"
    info = info + f"\nDateTime: {run_date} {run_time}"
    info = info + f"\n-------\nRATE MEASURES"
    for dest, dest_rm_info in rm_info.items():
        info = f"{info}\n{dest}"
        for rm_num, rm_num_info in dest_rm_info.items():
            info = f"{info}\n    RM Number: {rm_num}"
            for key, value in rm_num_info.items():
                info = f"{info}\n        {key}: {value}"

    check_bpms.writeInfo()
    info = info + check_bpms.getInfo()

    return info


def save_report(test_patt_report, run_date):
    """
    Saves the report of the passed or failed tests
    """

    epics_ctrls.break_point(f"saving reports to: {getReportFile(run_date)}")

    if not os.path.exists(getReportFile(run_date)):
        makeFile(getReportFile(run_date))
        report = {"0": test_patt_report}
        test_patt_report_json = json.dumps(report, indent=4)
        with open(getReportFile(run_date), "w") as report_file:
            report_file.write(test_patt_report_json)
        return

    with open(getReportFile(run_date), "r") as report_file:
        old_reports = dict(json.load(report_file))

    report_num = str(len(old_reports))
    report = {report_num: test_patt_report}

    old_reports.update(report)

    all_reports_json = json.dumps(old_reports, indent=4)

    with open(getReportFile(run_date), "w") as report_file:
        report_file.write(all_reports_json)


def saveData(*args, data_path=None):
    """
    Saves the raw data from the test sweet
    input
    --------
    *args: (tuples)
        data to be saved to data_path, dicts will be added together for a json dump
        e.x. {"dict_name": dict_data} where dict_data is of type dict
    data_path:
        variable name of data, needed for error outputs

    output
    --------
    Saves data to data_path
    """
    converted_args = {}
    for arg in args:
        converted_args[arg[0]] = tools.helpers.convertNumpyTypes(arg[1])

    try:
        json_data = json.dumps(converted_args, indent=4)
    except:
        epics_ctrls.break_point(f"unable to convert data for {data_path}")
        pass

    try:
        with open(data_path, "a") as data_file:
            data_file.write(json_data)

    except Exception as e:
        epics_ctrls.break_point(f"unable to save data for {data_path} becasue of {e}")


def testCurrentPattern(run_date, run_time):
    start = time.time()

    epics_ctrls.break_point(f"saving reports to: {getReportDir(run_date)}")

    if not os.path.exists(getReportDir(run_date)):
        os.mkdir(getReportDir(run_date))

    epics_ctrls.break_point(f"saving info to {getInfoFile(run_date)}")

    initInfoFile(run_date)

    test_patt_name = patt_sel.get_pattern_running()
    epics_ctrls.break_point(f"starting tests for {test_patt_name}")

    test_patt_report = initTestPattReport(test_patt_name, run_date, run_time)

    epics_ctrls.break_point("Collecting pattern data from the Nttable")
    test_patt_data = patt_sel.get_pattern_running_data()

    throughputs, pid_spacings, slow_dest_trigs = getMetaData(test_patt_name)

    patt_data = organizePattData(
        test_patt_data, throughputs, pid_spacings, slow_dest_trigs
    )
    print(patt_data)

    dest_buff_map = configureBuffers(patt_data)

    epics_ctrls.break_point(f"buffers initialized by destination {dest_buff_map}")

    check_bpms = initCheckBpms(dest_buff_map, epics_ctrls)

    check_bpms.monitorBsss(suffix="TMIT")
    check_bpms.monitorBsss(suffix="TMITPID")

    check_rms, rm_dest_rates, rm_dest_time_sources, slow_dest_reduced = initRms(
        throughputs, test_patt_data
    )

    epics_ctrls.break_point("Starting BSA Buffers")
    # start the aquisitions
    for dest_num in patt_data["Data"]:
        if patt_data["Data"][dest_num]["Active"]:
            patt_data["Data"][dest_num]["Buffer"].start()

    rm_info = checkRms(
        test_patt_report,
        slow_dest_trigs,
        check_rms,
        rm_dest_rates,
        rm_dest_time_sources,
        slow_dest_reduced,
    )

    # initialize bsa_ready flag to False before starting tests

    test_patt_report["Checks"]["bsa_buff_complete"] = waitForBsaData(patt_data)

    check_bpms.monitorBsssClear(suffix="TMIT")
    check_bpms.monitorBsssClear(suffix="TMITPID")

    check_bpms.getBpmBsaData(suffix="TMIT")
    check_bpms.getBpmBsaData(suffix="TMITPID")
    check_bpms.getTpgBsaData(tpg_base=TPG_BASE_PV, suffix="PIDL")

    check_bpms.calcSpacings(bpm_att="tmitpid_bsa")
    check_bpms.calcEntryCount(bpm_att="tmitpid_bsa")

    check_bpms.checkTmit()
    check_bpms.checkBsssAgainstBsa()

    releaseBuffers(patt_data)

    info = getInfo(run_date, run_time, test_patt_name, check_bpms, rm_info)

    print(info)

    # Save data

    data_path = getDataFile(test_patt_name, run_date, run_time)
    makeFile(data_path)

    epics_ctrls.break_point(f"saving data to: {data_path}")
    saveData(
        ("patt_data", patt_data),
        ("check_bpms", check_bpms.getBpmsAsDicts()),
        ("rm_info", rm_info),
        data_path=data_path,
    )

    rm_info = tools.helpers.convertNumpyTypes(rm_info)

    try:
        json_rm_info = json.dumps(rm_info, indent=4)
    except:
        print(f"undable to convert rm_info to json")

    # Save analysis of data
    epics_ctrls.break_point(f"saving info to: {getInfoFile(run_date)}")
    try:
        with open(getInfoFile(run_date), "a") as info_file:
            info_file.write(
                f"\n****************************Pattern Name: {test_patt_name} Start****************************"
            )
            info_file.write(f"\n")
            info_file.write(f"\nTime: {run_time}")

            info_file.write(check_bpms.getInfo())
            info_file.write("Rate Measure info:\n")
            info_file.write(json_rm_info)
            info_file.write(
                f"\n****************************Pattern Name: {test_patt_name} End****************************"
            )
    except:
        epics_ctrls.break_point("unable to save info")

    test_patt_report["Checks"]["has_good_tmit"] = check_bpms.checks["Expected TMIT"]
    test_patt_report["Checks"]["all_bsss_pid_in_bsa"] = check_bpms.checks[
        "BSSS tmitpid is a subset of BSA tmitpid"
    ]
    test_patt_report["Checks"]["bsss_tmit_match_bsa_on_pid"] = check_bpms.checks[
        "BSSS tmit data is a subset of BSA tmit data"
    ]

    save_report(test_patt_report, run_date)

    total_time = time.time() - start
    epics_ctrls.break_point(
        f"End of Pattern Verification.  Time to complete: {total_time} seconds"
    )


def getDateTime():
    """
    Return the date and time in a formatted ways
    outputs
    --------
    run_date:
        current date in YYYY-MM-DD format
    run_timef:
        current time in hh:mm:ss format
    """
    tod = datetime.datetime.now()
    tod_list = str(tod).split(" ")
    run_time = str(tod_list[1].split(".")[0])
    run_date = tod_list[0]
    return run_date, run_time


def applyAndTestPattern(pattern):
    """"""
    epics_ctrls.break_point(f"testing {pattern}")
    patt_sel.load_pattern(pattern)
    time.sleep(1)
    patt_sel.apply_pattern(pattern)
    time.sleep(5)
    run_date, run_time = getDateTime()
    testCurrentPattern(run_date, run_time)


def main():
    """"""

    if not args.RECURSIVE:
        run_date, run_time = getDateTime()
        testCurrentPattern(run_date, run_time)
        return

    if args.KEEP_RUNNING:
        while True:
            run_date, run_time = getDateTime()
            testCurrentPattern(run_date, run_time)
            time.sleep(10)

    epics_ctrls.break_point("recursive mode activated")

    test_patts = patt_sel.get_test_patterns()

    for pattern in test_patts:
        applyAndTestPattern(pattern)


if __name__ == "__main__":
    main()
