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

Author: Ryan McClanahan (rpm)
"""

from epics import caget, caput, camonitor, camonitor_clear
from edef import BSABuffer
import os
import ScPatternSelect
import check_bpm
import rm_checks
import time
import config
import argparse
import datetime
import socket
from re import split as re_split
import json
import argparse
from epics_script_controls import EpicsControls
import math
import numpy as np
import 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("--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), "info.txt")


def getReportFile(run_date):
    """"""
    return os.path.join(getReportDir(run_date), "reports.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 makeDataFile(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 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"info to {getInfoFile(run_date)}")

    initInfoFile(run_date)

    test_patt_name = patt_sel.get_pattern_running()
    epics_ctrls.break_point(test_patt_name)


def getDateTime():
    """
    Return the date and time in a formatted way
    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

    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()
