"""
Bsa verification script
This script gets ran by sioc-sys0-op03 aproximently every 15 minutes


"""
from epics import caget, caget_many, caput, PV
from edef import BSABuffer
import time
import sys
import subprocess
from pathlib import Path
import os
import argparse
import datetime
import glob
import numpy

#use Pass and Fail for tests
Pass = "PASS"
Fail = "FAIL"

parser = argparse.ArgumentParser()
parser.add_argument("destination", help="DST01, DST02, DST03, DST04, DSTSC")
parser.add_argument("eget_input", help="eget tag for program to get it's pvs from eg SCH --> eget_input = LCLS.SCH_FULL.BSA.rootnames.tag OUTPUT EGET BECOMES LCLS.SCH.BSA.rootnames.tag")
args = parser.parse_intermixed_args()

init_rate = 0

args.eget_input = f'LCLS.{args.eget_input}_FULL.BSA.rootnames'
# global eget_output 
eget_output = args.eget_input.replace("_FULL", "")

#path to log files
file_path = f'{os.environ["IOC_DATA"]}/../../reports/sc_bsa'
tod = datetime.datetime.now()
tod_list = str(tod).split(" ")
#make log file full names
log = Path(f'{file_path}/{tod_list[0]}-{args.destination}-log.txt')
bpm_log = Path(f'{file_path}/BPM-{tod_list[0]}-{args.destination}-log.txt')
human_readable_log = Path(f'{file_path}/{args.destination}-hr.txt')

def change_attribute(pv_list, new_attr):
    """
    changes the attribute of each pv in a list
    input
    --------
    pv_list:
        list of pvs
    new_attr:
        new attribute to substitute onto each pv in pv list
    --------
    Output
    pv_list_new_attr: 
        list of pvs with the new attr
    --------
    example
    pv_list = ['WIRE:BPN14:850:POSN']
    new_attr = TPR
    WIRE:BPN14:850:POSN -> WIRE:BPN14:850:TPR
    """
    pv_list_new_attr = []
    for pv in pv_list:
        if pv != None:
            pv_temp = pv.rsplit(":",1)
            pv_list_new_attr.append(pv_temp[0]+":"+new_attr)

    return pv_list_new_attr

def add_attribute(pv_list, attribute):
    """
    input
    --------
    pv_list:
        list of pvs
    attribute:
        new attribute to add onto each pv in pv list
    --------
    Output
    pv_list_new_attr: 
        list of pvs with the new attr
    --------
    example
    pv_list = ['WIRE:BPN14:850']
    new_attr = TPR
    WIRE:BPN14:850 -> WIRE:BPN14:850:TPR
    WIRE:BPN14:850: -> WIRE:BPN14:850:TPR
    """
    new_attribute_list = []
    for pv in pv_list:
        if pv != None:
            if pv.endswith(":"):
                pv = pv + attribute
                new_attribute_list.append(pv)
            else:
                pv = pv + ":" + attribute
                new_attribute_list.append(pv)
    return new_attribute_list

def eget_tag(tag):
    """
    input
    --------
    tag:
        string that is the full tag file to run the eget on
        Runs 'eget -ts ds -a tag={tag}'
    --------
    Output
    clean_eget_list: 
        returns the pvs from the eget in a list format
        cleaning done is to remove random characters form eget if len(pv)>3 then makes it into the clean_eget_list
    """
    check_latch()
    runtime_message(f'eget {tag}')
    try:
        eget_pvs = subprocess.check_output(f"eget -ts ds -a tag={tag}", shell=True)
    except:
        exit_message(f'failed eget, ds down?')
    
    eget_pvs = str(eget_pvs)
    eget_pvs = eget_pvs.replace("b'","") #random characters in the eget that need to be cleaned
    eget_list = eget_pvs.split("\\n") #split eget on new line to make the list
    clean_eget_list =[]

    for pv in eget_list:        
        #clean out some of the random characters from the eget list
        #pvs should have a len much greater than 3 (10 seems to be the lowest)
        if len(pv) > 3:
            clean_eget_list.append(pv)
        
    return clean_eget_list

def pv_list_from_dict(ROOTNAMES_dict):
    """
    Makes a pv list based off of the pv keys in the ROOTNAMES_dict
    used for caget_many, as it requires a list

    input
    --------
    ROOTNAMES_dict:
        Dictionary where all the keys are pvs
        Each PV is a dictionary with metadata/checks from this script
    --------
    Output
    pv_list: 
        list of pvs in the ROOTNAMES_dict
    """
    pv_list = []
    for pv in ROOTNAMES_dict:
        pv_list.append(pv)
    return pv_list

def check_pv_connection(ROOTNAMES_dict):
    """
    Checks if the pv in pv dict returns a value or a 'None' from a caget
    Sets the first element in the pv's dictionary in ROOTNAMES_dict to 0 if it returns a value, 1 if it does not
    Actually cagets .[-1] because the pvs are big arrays
    input
    --------
    ROOTNAMES_dict:
        Dictionary where all the keys are pvs
        Each PV is a dictionary with metadata/checks from this script
    --------
    Output
    ROOTNAMES_dict:
        Dictionary where all the keys are pvs
        Each PV is a dictionary with metadata/checks from this script
    --------
    example
    for a pv entry in ROOTNAMES_dict

    pv = {'CONNECTION': Fail} if the pv is connected
    pv = {'CONNECTION': Pass} if the pv is not connected
    """
    check_latch()
    runtime_message('checking connections')

    pv_list =[]
    #need to make a list of the pvs for the caget_many
    #add '.[-1]' because pvs are big arrays
    for pv in ROOTNAMES_dict:
        pv_list.append(f'{pv}.[-1]')
    values = caget_many(pv_list,timeout=3)

    #check values to see if there is connection
    for index, pv in enumerate(ROOTNAMES_dict):
        if str(values[index]) == 'None':
            ROOTNAMES_dict[pv]["CONNECTION"]=Fail
        else:
            ROOTNAMES_dict[pv]["CONNECTION"]=Pass
    return ROOTNAMES_dict

def set_tpr(ROOTNAMES_dict):
    """
    replaces the attribute of the pv in ROOTNAMES with TPR, then cagets the <rootnamepv>:TPR to find the TPR the pv is listening to
    sets pv[TPR] to none if no tpr
    """
    check_latch()
    runtime_message("finding tprs")
    pv_list = pv_list_from_dict(ROOTNAMES_dict)
    pv_list = change_attribute(pv_list, "TPR")
    tpr_list = caget_many(pv_list,timeout=3)
    for index, pv in enumerate(ROOTNAMES_dict):
        ROOTNAMES_dict[pv]["TPR"]=tpr_list[index]

    return ROOTNAMES_dict

def get_tpr_list(ROOTNAMES_dict):
    """
    Makes a list of tprs from the ROOTNAMES_dict
    Strips out the tprs that returned None

    input
    ------
    ROOTNAMES_dict:
        dictionary that holds all the pvs and the colected meta data on the pvs
    output
    ------
    tpr_list:
        list of the tprs the pvs in ROOTNAMES_dict are listing to
        Nones are stripped for increased speed of caget_many
    """
    check_latch()
    tpr_list =[]
    #get the list of tprs
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["TPR"] != None:
            tpr_list.append(ROOTNAMES_dict[pv]["TPR"])
    return tpr_list

def facmode_num_to_str(facmode):
    """
    converts the facmode to a string
    0 = NC
    1 = SC
    """
    if facmode == 0:
        return 'NC'
    if facmode ==1:
        return 'SC'
    else:
        return None

def set_tpr_mode_match(ROOTNAMES_dict,soft_facmode,hard_facmode):
    """
    sets the tpr mode, and the tpr mode match fields in the ROOTNAMES_dict

    inputs
    ------
    ROOTNAMES_dict
        dictionary that holds all the pvs and the colected meta data on the pvs
    soft_facmode
        the facility mode for the solfline, 0 = NC, 1 = SC
    hard_facmode
        the facility mode for the hardline, 0 = NC, 1 = SC

    output
    ------
    ROOTNAMES_dict
        dictionary that holds all the pvs and the colected meta data on the pvs
        updated with TPR_MODE and TPR_MODE_MATCH data
    """
    check_latch()
    #todo: remove from eget if in a different mode
    #report that it is in a different mode, not failed
    runtime_message("checking tpr mode")
    soft_areas = ['LTUS','UNDS','DMPS','FEES']
    hard_areas = ['LTUH','UNDH','DMPH','FEEH']
    tpr_list = get_tpr_list(ROOTNAMES_dict)

    #tpr pvs are stored without the mode attribute
    #also strips out the Nones
    tpr_list = add_attribute(tpr_list, "MODE")
    #get the list of modes
    mode_list = caget_many(tpr_list,timeout=3)

    #need to manualy make index and increment it, because mode_list is not the same length as ROOTNAMES_dict
    index=0
    for pv in ROOTNAMES_dict:
        #Nones have been cleaned from mode_list
        #stor mode in string form
        if ROOTNAMES_dict[pv]["TPR"]!=None:
            ROOTNAMES_dict[pv]["TPR_MODE"]=facmode_num_to_str(mode_list[index])
            index = index +1
        else:
            ROOTNAMES_dict[pv]["TPR_MODE"]=None
        ROOTNAMES_dict[pv]["TPR_MODE_MATCH"]=None #set all mode match to none, then look at it in soft or hard

    #soft and hardline pvs need to match the mode of the tpr
    #check that here
    for pv in ROOTNAMES_dict:
        
        #single out softline pvs and check against the softline facility mode
        if(pv.__contains__(soft_areas[0]) or pv.__contains__(soft_areas[1]) or 
           pv.__contains__(soft_areas[2]) or pv.__contains__(soft_areas[3])):
            if ROOTNAMES_dict[pv]["TPR_MODE"]==soft_facmode:#implement mode match check
                ROOTNAMES_dict[pv]["TPR_MODE_MATCH"]="Match"
            else:
                ROOTNAMES_dict[pv]["TPR_MODE_MATCH"]="Not Matched"

        #single out hardline pvs and check against the hardline facility mode
        if(pv.__contains__(hard_areas[0]) or pv.__contains__(hard_areas[1]) or 
           pv.__contains__(hard_areas[2]) or pv.__contains__(hard_areas[3])):
            if ROOTNAMES_dict[pv]["TPR_MODE"]==hard_facmode:#implement mode match check
                ROOTNAMES_dict[pv]["TPR_MODE_MATCH"]="Match"
            else:
                ROOTNAMES_dict[pv]["TPR_MODE_MATCH"]="Not Matched"

    return ROOTNAMES_dict

def set_tpr_rxlnkstatus(ROOTNAMES_dict):
    """
    checks the rxlnkstatus of the tpr and set it as RXLNKSTATUS in the ROOTNAMES_dict
    """
    check_latch()
    runtime_message("checking rxlnkstatus")
    tpr_list = get_tpr_list(ROOTNAMES_dict)
    #tpr pvs are stored without the mode attribute
    #also strips out the Nones
    tpr_RXLNKSTATUS_list = add_attribute(tpr_list, "RXLNKSTATUS")
    RXLNKSTATUS_list = caget_many(tpr_RXLNKSTATUS_list,timeout=3)
    #need to manualy make index and increment it, because mode_list is not the same length as ROOTNAMES_dict
    index=0
    for pv in ROOTNAMES_dict:
        #Nones have been cleaned from mode_list
        #check if 
        if ROOTNAMES_dict[pv]["TPR"]!=None:
            #RXLNKSTATUS pv is reversed, we want 0 to mean that the checks were passed
            if RXLNKSTATUS_list[index] == 1:
                ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"]=Pass
            elif RXLNKSTATUS_list[index] == None:
                ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"]='None'
            else:
                ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"]=Fail
            index = index +1
        else:
            ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"]='None'

    return ROOTNAMES_dict

def print_ROOTNAMES(ROOTNAMES_dict):
    for pv in ROOTNAMES_dict:
        print (pv + str(ROOTNAMES_dict[pv]))
    
def set_pid_nord(ROOTNAMES_dict):
    """
    Check the PID and the Nord for the pvs
    """
    check_latch()
    #pid = timestamp of pv+'HST'+str(bsa_buff.number)
    #or pid = pv+'HST'+str(bsa_buff.number).[-1]
    #nord = pv + 'HST' + str(bsa_buff.number) + '.NORD'
    
    runtime_message("checking pid and nord")

    PIDLPID_str = str(f'TPG:SYS0:1:PIDLPIDHST{bsa_buff.number}')
    PIDLPID_ref = PV(PIDLPID_str)
    nord_ref = caget(f'BSA:SYS0:1:{bsa_buff.number}:MEASCNT')

    PV_list = [] #using capitals since they are PV objects from the epics package

    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["CONNECTION"]==Pass: #only want connected pvs
            PV_list.append(PV(pv))
        #set everything to 0, then set stuff that passes checks to 1 in next for statement
        ROOTNAMES_dict[pv]["NORD_CHECK"]=Fail
        ROOTNAMES_dict[pv]["NORD"]=Fail
        ROOTNAMES_dict[pv]["PID_CHECK"]=Fail
        ROOTNAMES_dict[pv]["PID"]=Fail

    for PV_object in PV_list:
        #check nord and pid
        pv = PV_object.pvname
        #
        ROOTNAMES_dict[pv]["NORD"]=PV_object.count
        ROOTNAMES_dict[pv]["PID"]=PV_object.timestamp
        if ROOTNAMES_dict[pv]["NORD"] == nord_ref:  
            ROOTNAMES_dict[pv]["NORD_CHECK"]=Pass#if nord ok and connected passed nord check
        if ROOTNAMES_dict[pv]["PID"] == PIDLPID_ref.timestamp:
            ROOTNAMES_dict[pv]["PID_CHECK"]=Pass#if pid ok and connected passed pid check
    return ROOTNAMES_dict

def get_disconnected_pvs(ROOTNAMES_dict):
    disconnected_pvs = []
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["CONNECTION"] == Fail:
            disconnected_pvs.append(pv)
    print('disconnected_pvs')
    print(disconnected_pvs)
    return disconnected_pvs

def get_no_tpr(ROOTNAMES_dict):
    no_tpr_pvs=[]
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["TPR"] == None:
            no_tpr_pvs.append(pv)
    print('no tpr')
    print(no_tpr_pvs)
    return no_tpr_pvs

def get_tpr_missmatch(ROOTNAMES_dict):
    miss_match=[]
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["TPR_MODE_MATCH"] == Fail:
            miss_match.append(pv)
    print('miss_match')
    print(miss_match)
    return miss_match

def get_bad_nord(ROOTNAMES_dict):
    bad_nord=[]
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["NORD_CHECK"] == Fail:
            bad_nord.append(pv)
    print('bad_nord')
    print(bad_nord)
    return bad_nord

def get_bad_pid(ROOTNAMES_dict):
    bad_pid=[]
    for pv in ROOTNAMES_dict:
        if ROOTNAMES_dict[pv]["PID_CHECK"] == Fail:
            bad_pid.append(pv)
    print('bad_pid')
    print(bad_pid)
    return bad_pid

def export_pvs_to_log(ROOTNAMES_dict):
    """
    Writes to log file $IOC_DATA/../../reports/sc_bsa/MM-DD-YYYYlog.txt
    If a file does not exist it creates one

    """
    check_latch()
    runtime_message("writing to log")

    if log.exists():
        with open (log, "a") as log_file:
            log_file.writelines(f'\n\nTime of Day: {tod_list[1]}\n')
            for pv in ROOTNAMES_dict:
                if Fail in ROOTNAMES_dict[pv].values():
                    log_file.writelines(pv + str(ROOTNAMES_dict[pv]) + '\n')
    else:
        with open (log, "x") as log_file:
            log_file.writelines(f'Time of Day: {tod_list[1]}\n')
            for pv in ROOTNAMES_dict:
                if Fail in ROOTNAMES_dict[pv].values():
                    log_file.writelines(pv + str(ROOTNAMES_dict[pv]) + '\n')

def export_pvs_to_bpm_log(ROOTNAMES_dict):
    """
    Writes to log file $IOC_DATA/../../reports/sc_bsa/BPM-MM-DD-YYYYlog.txt
    If a file does not exist it creates one

    """
    check_latch()
    runtime_message("writing to BPM log")

    if bpm_log.exists():
        with open (bpm_log, "a") as bpm_log_file:
            print("appending")
            bpm_log_file.writelines(f'\n\nTime of Day: {tod_list[1]}\n')
            for pv in ROOTNAMES_dict:
                if Fail in ROOTNAMES_dict[pv].values():
                    if pv.__contains__("BPMS:") or pv.__contains__("TPG:"):
                        if ROOTNAMES_dict[pv]['CONNECTION'] == Pass:
                            bpm_log_file.writelines(pv + str(ROOTNAMES_dict[pv]) + '\n')
    else:
        with open (bpm_log, "x") as bpm_log_file:
            print("overwriting")
            bpm_log_file.writelines(f'Time of Day: {tod_list[1]}\n')
            for pv in ROOTNAMES_dict:
                if Fail in ROOTNAMES_dict[pv].values():
                    if pv.__contains__("BPMS:") or pv.__contains__("TPG:"):
                        if ROOTNAMES_dict[pv]['CONNECTION'] == Pass:
                            bpm_log_file.writelines(pv + str(ROOTNAMES_dict[pv]) + '\n')

def write_with_spaces(log_file, word, total_len):
    """
    writes spaces after the word to get to the todal_len
    """
    word_len = len(word)
    log_file.writelines(word)
    while word_len < total_len:
        log_file.writelines(" ")
        word_len = word_len+1

def write_pv_to_hr_log(log_file, ROOTNAMES_dict, pv):
    """
    Writes on pv to the human readable log
    """
    write_with_spaces(log_file, pv, 35)
    log_file.writelines("|  ")

    if ROOTNAMES_dict[pv]["CONNECTION"]==Pass:
        write_with_spaces(log_file, "connected", 15)
        log_file.writelines("|  ")
    else:
        write_with_spaces(log_file, "disconnected", 15)
        log_file.writelines("|  ")

    write_with_spaces(log_file, f'PID: {ROOTNAMES_dict[pv]["PID"]}', 25)
    log_file.writelines("|  ")

    write_with_spaces(log_file, f'NORD: {ROOTNAMES_dict[pv]["NORD"]}', 15)
    log_file.writelines("|  ")

    log_file.writelines("RX Link: ")

    if ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"] == 'None':
        write_with_spaces(log_file, "No TPR", 7)
        log_file.writelines("|  ")
    elif ROOTNAMES_dict[pv]["TPR_RXLNKSTATUS"] == Fail:
        write_with_spaces(log_file, "down", 7)
        log_file.writelines("|  ")
    else:
        write_with_spaces(log_file, "up", 7)
        log_file.writelines("|  ")

    write_with_spaces(log_file, f'TPR MODE: {ROOTNAMES_dict[pv]["TPR_MODE"]}', 15)

    log_file.writelines("\n")

def export_pvs_to_hr_log(ROOTNAMES_dict):
    """
    writes a more human readable file
    """
    check_latch()
    failed_pvs = {}
    passed_pvs = {}
    disconnected_pvs = {}
    for pv in ROOTNAMES_dict:
        if Fail in ROOTNAMES_dict[pv].values() and ROOTNAMES_dict[pv]["CONNECTION"]==Pass:
            failed_pvs[pv]=ROOTNAMES_dict[pv]
        elif Fail in ROOTNAMES_dict[pv].values() and ROOTNAMES_dict[pv]["CONNECTION"]==Fail:
            disconnected_pvs[pv]=ROOTNAMES_dict[pv]
        else:
            passed_pvs[pv]=ROOTNAMES_dict[pv]
    try:
        with open(human_readable_log, "w") as log_file:
            log_file.writelines(["#human readable log file for bsa, updates every 5 minutes, pvs that failed bsa are first\n",
                                    f'#for all pvs trying to participate in bsa use \'eget -ts ds -a tag={args.eget_input}\'\n',
                                    f'#all pvs that have passed the checks can be gotten with \'eget -ts ds -a tag={eget_output}\'\n'])
            
            log_file.writelines("\n***** Disconnected PVS *****\n")
            for pv in disconnected_pvs:
                write_pv_to_hr_log(log_file, disconnected_pvs, pv)

            log_file.writelines("\n***** Failed PVS *****\n")
            for pv in failed_pvs:
                write_pv_to_hr_log(log_file, failed_pvs, pv)

            log_file.writelines("\n***** Passed PVS *****\n")
            for pv in passed_pvs:
                write_pv_to_hr_log(log_file, passed_pvs, pv)

    except:
        runtime_message("Error with hr log")

def write_eget_tag(ROOTNAMES_dict, eget_output):
    """
    Writes the new eget tag file
    """
    check_latch()
    runtime_message(f"writing to {eget_output}")
    """
    OPEN old tag file, read in the comments and write them to new tag file,
    make sure end of file tag is at end of file
    """

    eget_input = Path(f'{os.environ["IOC_DATA"]}/../ds_tags/{args.eget_input}.tag')
    eget_output = Path(f'{os.environ["IOC_DATA"]}/../ds_tags/{eget_output}.tag')

    if eget_output.exists():
        os.remove(eget_output)

    if eget_input.exists():
        with open(eget_output, "x") as output:
            with open(eget_input, "r") as input: 
                for input_line in input:
                    if input_line.startswith('#') and not input_line.__contains__('EOF'):
                        output.writelines(input_line)
            output.writelines(f'#see {args.eget_input} for original replacements on %CNTHSTTH\n\n')
            output.writelines([f'#This list has been pared down from {args.eget_input} based on\n',
                               '#1. pv connection\n',
                               '#2. \n'])
            #close input
            for pv in ROOTNAMES_dict:
                if Fail not in ROOTNAMES_dict[pv].values():
                    root_pv = pv.split("HST")
                    output.writelines(f's/{root_pv[0]}CNTHSTSCBTH/{root_pv[0]}/g\n')
            output.writelines(f'\n\n#\n#[EOF]')

def get_and_check_rate():
    """
    Returns rate for destination, (SCS+SCH for DSTSC)
    Exits if rate is 0

    output
    ------
    rate:
        rate returned by caget on TPG:SYS0:1:{args.destination}:RATE or DST03:RATE + DST04:RATE for DSTSC
    """
    if args.destination == 'DSTSC':
        rate1 = caget(f'TPG:SYS0:1:DST03:RATE')
        rate2 = caget(f'TPG:SYS0:1:DST04:RATE')
        rate = rate1 + rate2
        if rate1==0 or rate2==0:
            rate_flag=False 

    else:
        rate = caget(f'TPG:SYS0:1:{args.destination}:RATE')
        if rate == 0:
            rate_flag = False
        else: rate_flag = True

    if not rate_flag:
        exit_message('rate <= 0')

    return rate

def check_latch():
    """
    Makes sure that the LATCH_STS PV is ok and not latched
    If it is latched exit the program
    Don't need to include the case if the
    """
    latch = caget(f'BSA:SYS0:1:{args.destination}:LATCH_STS')
    if  latch != 0:
        exit_message('Script is latched')
    else:
        pass

def rate_init():
    """
    Checks the rate for the destination
    if rate is <= 0 the program aborts and exits
    """
    runtime_message('checking initial rate')
    rate_flag, rate = get_rate()

    if not rate_flag:
        exit_message('rate <= 0')

    init_rate = rate

def check_facmode(soft_facmode, hard_facmode):
    """
    Checks facmode for the destination
    if facmode is NC the program aborts and exits
    """
    if args.destination == 'DSTSC' or args.destination == 'DST03' or args.destination == 'DST04':
        runtime_message('checking facility mode')
        #might want to change this to a caget many

        if args.destination == 'DSTSC':
            if soft_facmode == 0:
                exit_message('soft line is in NC')
            if hard_facmode == 0:
                exit_message('hard line is in NC')
        
        if args.destination == 'DST03' and hard_facmode == 0:
            exit_message('hard line is in NC')
            
        if args.destination == 'DST04' and soft_facmode == 0:
            exit_message('soft line is in NC')

def runtime_message(string):
    """
    caputs the string to the string pv that recieves messages during run time
    If in test mode, prints to terminal
    input
    ------
    string:
        string that can be no more than 40 characters long
        If not a string it is cast to a string and
        If longer than 40 characters it is reduced to 40 characters befor the caput or print
    output
    ------
    none:
        returns nothing, writes message to 
    """
    string = str(string)#make sure this is a string
    if len(string)>40: #epics pvs can only handle a charcter length of 40
        string = string[:40]
    
    caput(f"BSA:SYS0:1:{args.destination}:LAUNCH_STS", string)#for runtime, need actual pv
    return

def log_message(message):
    """
    writes the message to the log
    """
    if log.exists():
        with open (log, "a") as log_file:
            log_file.writelines(f'\n\nTime of Day: {tod_list[1]}\n')
            log_file.writelines(f'{message}\n')
    else:
        with open (log, "x") as log_file:
            log_file.writelines(f'Time of Day: {tod_list[1]}\n')
            log_file.writelines(f'{message}\n')

def exit_message(message):
    """
    Writes the "EXITING: message" to the runtime pv and the log, then exits the program
    """
    message = 'EXITING: '+ message
    runtime_message(message)
    log_message(message)
    try:
        bsa_buff
    except:
        pass
    else:bsa_buff_release()
    sys.exit()

def delete_old_logs(days_to_keep):
    """
    deletes the log files older than the days_to_keep
    I.E. if days_old = 1 only the current day's log files will survive
         if days_old = 7 then the last 7 days of log files will survive

    input
    ------
    days_to_keep:
        int
        how many days of log files to keep

    output
    ------
    none:
        writes to log file
    """
    date_format = '%Y-%m-%d'

    days_to_keep = int(days_to_keep)

    if days_to_keep <1:
        days_to_keep = 1

    logs_to_keep = []

    #make a list of dates that are safe
    for day_delta in range(0,days_to_keep):
        date_to_keep = datetime.datetime.strptime(tod_list[0], date_format) - datetime.timedelta(days=day_delta)
        date_to_keep = str(date_to_keep)
        date_to_keep = date_to_keep.split(" ")
        date_to_keep = date_to_keep[0]
        logs_to_keep.append(date_to_keep)

    #compair
    for clean_up in glob.glob(f'{file_path}/*{args.destination}*'):
        head, tail = os.path.split(clean_up)
        tail_date = tail[0:10]
        if tail_date not in logs_to_keep:
            if "hr" not in clean_up:
                os.remove(clean_up)

def bsa_buff_get_dest():
    """
    output
    ------
    dest_mask:
        list of dest masks for the bsa aquisition
    dest_num:
        list of dest masks in number form for bsa aquisition
    """
    dest_masks = caget_many([f'BSA:SYS0:1:21:DST0.DESC', f'BSA:SYS0:1:21:DST1.DESC', f'BSA:SYS0:1:21:DST2.DESC', 
                         f'BSA:SYS0:1:21:DST3.DESC', f'BSA:SYS0:1:21:DST4.DESC', f'BSA:SYS0:1:21:DST5.DESC'])

    if args.destination != "DSTSC":
        dest_num = []
        temp = str(args.destination).split('0')
        temp = int(temp[1])
        dest_num.append(temp)
        dest_mask = []
        dest_mask.append(dest_masks[temp])
    else:
        dest_mask = []
        dest_num = [3,4]
        dest_mask.append(dest_masks[3])
        dest_mask.append(dest_masks[4])

    return dest_mask, dest_num

def bsa_buff_configure(bsa_buff, dest_mask, 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:SYS0:1:{bsa_buff.number}:DST{index}', 0)

    #write to destination mode pv, want inclusion  
    caput(f'BSA:SYS0:1:{bsa_buff.number}:DESTMODE', 2)

    #write to all aplicable dest mask pvs
    for index, dest in enumerate(dest_mask):
        caput(f'BSA:SYS0:1:{bsa_buff.number}:DST{dest_num[index]}', 1)
    time.sleep(1) #need this or else the buffer will start before the inclusion mask is set

    bsa_buff.n_measurements = numpy.random.randint(50)

def bsa_buff_check_state():
    """
    Check the state of the bsa buffer if it is running then exit
    """
    ready = caget(f'BSA:SYS0:{bsa_buff.number}:HST_READY')
    if ready == 0:
        exit_message('buffer in use')

def bsa_buff_release():
    """
    WIP: need to make a pv for this
    Default to keeping the same buffer for now :)
    Only release bsa_buff if we option for it is selected
    """
    if buff_on:
        caput(f'BSA:SYS0:{bsa_buff.number}:HST_READY',1)
    #bsa_buff.release()
    pass

#--------------------start of main program--------------------
runtime_message(f'bsa health check starting for {args.destination}')
buff_on = False
check_latch()
delete_old_logs(2)
soft_facmode = caget('PHYS:UNDS:1:FACMODE')
hard_facmode = caget('PHYS:UNDH:1:FACMODE')

soft_facmode = facmode_num_to_str(soft_facmode)
hard_facmode = facmode_num_to_str(hard_facmode)

check_facmode(soft_facmode, hard_facmode)
get_and_check_rate()
dest_mask, dest_num = bsa_buff_get_dest()


bsa_buff = BSABuffer(f'BSA Check', user="timing team")
#check if buffer is ok to use, configure it, then start it
bsa_buff_check_state()
#put to ready so other destinations dont reserve
caput(f'BSA:SYS0:{bsa_buff.number}:HST_READY',0) 
bsa_buff_configure(bsa_buff, dest_mask, dest_num)
bsa_buff.start()
buff_on = True

ROOTNAMES_dict = {}

eget = eget_tag(args.eget_input)

for pv in eget:
    pv_dict=dict()
    pv = f'{pv}HST{bsa_buff.number}'
    ROOTNAMES_dict[pv]=pv_dict

runtime_message('waiting for bsa aquisition')
#acqusition has been running for some time now. Make sure it is done before checking the acquisition pvs
while caget(f'BSA:SYS0:{bsa_buff.number}:HST_READY') == 0:
    time.sleep(0.1)
    runtime_message("checking bsa ready pv")
    check_latch()

#want to keep this to "NOT READY" until the script is done evaluating the data
#so that this script launched with different destinations don't step on eachother's
#toes
caput(f'BSA:SYS0:{bsa_buff.number}:HST_READY',0)

ROOTNAMES_dict = check_pv_connection(ROOTNAMES_dict)
ROOTNAMES_dict = set_tpr(ROOTNAMES_dict)
ROOTNAMES_dict = set_tpr_mode_match(ROOTNAMES_dict,soft_facmode,hard_facmode)
ROOTNAMES_dict = set_tpr_rxlnkstatus(ROOTNAMES_dict)

#do the acquisition health checks after this, as acquisition needs to be complete
runtime_message('bsa aquisition complete')

#Some Nords take a little time to update.  Giving them a little buffer time too finish up
#Might want to not hard code this eventualy
for i in range(30):
    check_latch()
    time.sleep(1)

ROOTNAMES_dict = set_pid_nord(ROOTNAMES_dict)

#done with checking pid's and nords, let this script launched with other destinations
#have access to the buffer
caput(f'BSA:SYS0:{bsa_buff.number}:HST_READY',1)

export_pvs_to_log(ROOTNAMES_dict)
export_pvs_to_bpm_log(ROOTNAMES_dict)
export_pvs_to_hr_log(ROOTNAMES_dict)
write_eget_tag(ROOTNAMES_dict, eget_output)
runtime_message('COMPLETE')
bsa_buff_release()