"""
Script controls and readbacks for verify_pattern.py
"""

from epics import caget, caput
import time
from threading import Thread


class EpicsControls:
    EXIT = 0
    RUN = 1
    PUASE = 2
    def __init__(self, base_pv: str, terminalMessages: bool = False, 
                 pvMessages: bool = False, heartbeat: bool = False,
                 allowDuplicates: bool = False):
        """
        base_pv: base pv to add suffixes for messages, control, and heartbeat
                 {base_pv}_MSG, {base_pv}_CTRL, and {base_pv}_HRTBT respectively
        
        terminalMessages: Weather or not to send messages to the terminal
        
        pvMessages: Wheater or not to send messages to the message pv
        
        heartbeat: Wheather or not to start a heartbeat thread

        allowDuplicates: Checks that the ctrl pv is in exit and hrtbt pv is not incrimenting
        """
        self.base_pv = base_pv
        self.terminalMessages = terminalMessages
        self.pvMessages = pvMessages
        self.msg_pv = f'{base_pv}_MSG'
        self.ctrl_pv = f'{base_pv}_CTRL'
        self.hrtbt_pv = f'{base_pv}_HRTBT'
        if not allowDuplicates:
            self.check_duplicates()
        caput(self.ctrl_pv, 'RUN')
        if heartbeat:
            self.start_heartbeat()

    def runtime_message(self, message: str):
        """
        caputs the string to the string pv that recieves messages during run time
        If in test mode, prints to terminal
        If using ctrl pv, use break_point to write messages
        input
        ------
        message: message to write to pv or terminal

        output
        ------
        none:
            returns nothing, writes message to message pv or terminal depending on terminalMessages
        """
        if self.terminalMessages:
            print(message)

        if self.pvMessages:
            message_put = caput(self.msg_pv, message)
            if message_put is None:
                print(f"{self.msg_pv} is unavailable")
        return
    
    def break_point(self, message: str):
        """
        break_point for script, checks control pv for input
        Writes message with runtime_message
        """
        ctrl_val = caget(self.ctrl_pv)
        cur_time = time.strftime("%H:%M:%S", time.localtime())

        if ctrl_val == EpicsControls.EXIT:
            self.runtime_message(f'{cur_time} | PV EXIT  | {message}')
            exit(1)

        if ctrl_val == EpicsControls.RUN:
            self.runtime_message(f'{cur_time} | PV RUN   | {message}')
            return
        
        if ctrl_val == EpicsControls.PUASE:
            self.runtime_message(f'{cur_time} | PV PAUSE | {message}')
            while ctrl_val == EpicsControls.PUASE:
                ctrl_val = caget(self.ctrl_pv)
                time.sleep(0.2)
        
    def start_heartbeat(self):
        """
        starts a thread that writes to the heartbeat
        """
        print("start heartbeat")
        hrtbt_thread = Thread(target= self.heartbeat, daemon= True)
        hrtbt_thread.start()

    def heartbeat(self):
        """
        caput to heartbeat pv at 0.1 sec interval
        """
        counter = 0
        while True:
            try:
                caput(self.hrtbt_pv, counter)
            except:
                print('Heartbeat error')
            time.sleep(0.1)
            counter = counter + 1

    def check_duplicates(self):
        """
        checks for duplicates using ctrl pv and hrtb pv
        """