"""
Pattern verification script
Verifies the spacing in a pattern using bsa


"""

from epics import caget, caget_many, camonitor, camonitor_clear
import functools
import numpy as np
import math
from dataclasses import dataclass, field
from config import BSA_BUFF_LOW, BSA_BUFF_HIGH, BPM_CONFIG, BPM_TMIT_LIMIT
from tools.epics_script_controls import EpicsControls
import tools.helpers as helpers
from re import split as re_split


@dataclass
class Bpm:
    """
    data class for storeing Bpm data including bsss and bsa data collected
    """

    pv_name: str
    """base pv name of the BPM I.e. BPMS:HTR:960"""
    dest: int
    """destination the bpm is used for"""
    tmit_req: bool
    """True if tmit required, False if tmit required to be 0"""
    _bsa_buff_num: int = field(default=0)
    """buffer number associated with the BPM (21-49)"""
    tmit_bsa: list = field(default_factory=list)
    """tmit bsa data associated with the bpm and bsa_buff_num"""
    tmit_bsss: list = field(default_factory=list)
    """tmit bsss data associated with the bpm and bsa_buff_num"""
    tmitpid_bsa: list = field(default_factory=list)
    """pid bsa data associated with the bpm and bsa_buff_num"""
    tmitpid_bsss: list = field(default_factory=list)
    """pid bsss data associated with the bpm and bsa_buff_num"""
    tmitpid_bsa_spacings: list = field(default_factory=list)
    """pid spacing between the pid_bsa data"""
    tmitpid_bsa_spacing_count: dict[int] = field(default_factory=list)
    """key: pid_spacing, value: count of pid spacing"""
    pidl_bsa: list = field(default_factory=list)
    """tpg pid buffer history"""
    n_expected_tmit: int = 0
    has_expected_tmit: bool = True
    all_bsss_pid_in_bsa: bool = True
    all_bsss_data_in_bsa: bool = True
    summary: str = ""
    """string summary of the bpm"""

    @property
    def bsa_buff_num(self):
        return self._bsa_buff_num

    @bsa_buff_num.setter
    def bsa_buff_num(self, value):
        """Set to 0 if set outside of possible bsa buff nums (21-49)"""
        print(value)
        if value < BSA_BUFF_LOW or BSA_BUFF_HIGH < value:
            self._bsa_buff_num = 0
            return
        self._bsa_buff_num = value


class CheckBpm:
    def __init__(self, bpm_configs: dict, buff_nums: dict, epics_ctrls: EpicsControls):
        """
        Initialize the CheckBpm Object.  Holds data from bpms and tests/checks for the bpms
        """
        self._bpms = []
        self.buff_nums = buff_nums
        self.epics_ctrls = epics_ctrls
        self.epics_ctrls.break_point("CheckBpm init start")
        for dest, buff_num in buff_nums.items():
            for bpm in bpm_configs[dest]:
                self.epics_ctrls.break_point(
                    f"initializing {bpm[0]}, tmit_req={bpm[1]}"
                )
                self.add_bpm(bpm[0], dest, bpm[1], buff_num)
        self.epics_ctrls.break_point("CheckBpm init start")
        self.checks = {}

    @property
    def bpms(self):
        return self._bpms

    def add_bpm(self, name, dest, tmit_req, buff_num):
        bpm = Bpm(pv_name=name, dest=dest, tmit_req=tmit_req)
        bpm.bsa_buff_num = buff_num
        self._bpms.append(bpm)

    def bpmsCount(self):
        return len(self.bpms)

    @staticmethod
    def forEveryBpm(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            for bpm_idx in range(self.bpmsCount()):
                func(self, bpm_idx, **kwargs)
            return

        return wrapper

    @forEveryBpm
    def printBpms(self, bpm_idx: int, **kwargs):
        print(self._bpms[bpm_idx])

    @forEveryBpm
    def monitorBsss(self, bpm_idx: int, suffix: str):
        """
        Start a monitor on all of the bpms
        usage: monitorBsss(sufffix="suffix")
        input
        --------
        bpm_idx:
            index of the bpm provided by the function wrapper
        suffix:
            suffix of the bpm pv for bsss monitoring. I.e. TMIT or TMITPID

        output
        --------
        None

        side effects
        -------
        Sets the bsss data for the suffix for each bpm in self.bpms
        """
        bsss_pv = f"{self.bpms[bpm_idx].pv_name}:{suffix.upper()}{self.bpms[bpm_idx].bsa_buff_num}"
        bsss_val = caget(bsss_pv, timeout=0.5)
        if bsss_val is None:
            self.epics_ctrls.break_point(f"Info: cannot connect to bsss pv {bsss_pv}")
        else:
            self.epics_ctrls.break_point(f"Info: connected to bsss pv {bsss_pv}")
            camonitor(
                bsss_pv,
                writer=helpers.bsssWriter,
                callback=self.monitorBsssCallback,
            )

    def monitorBsssCallback(self, **kwargs):
        """
        Callback for the bsss monitor
        """
        bpm_name, trash, attribute = kwargs["pvname"].rpartition(
            ":"
        )  # separate the bpm name and the attribute
        suffix, buff_num = filter(
            None, re_split(r"(\d+)", attribute)
        )  # sepparate the suffix and the buff_num from the attribute of the pvname
        value = (
            0 if math.isnan(kwargs["value"]) else int(kwargs["value"])
        )  # some values are nan, want these to be ints
        for bpm_idx, bpm in enumerate(self.bpms):  # find the bpm
            if bpm.pv_name == bpm_name:
                break
        bsss_lst = getattr(
            self.bpms[bpm_idx], f"{suffix.lower()}_bsss"
        )  # add the new value to the bsss list
        bsss_lst.append(value)
        setattr(self.bpms[bpm_idx], f"{suffix.lower()}_bsss", bsss_lst)

    @forEveryBpm
    def monitorBsssClear(self, bpm_idx: int, suffix: str) -> None:
        """
        Clear the bsss monitor when done
        usage: monitorBsssClear(sufffix="suffix")
        input
        --------
        bpm_idx:
            index of the bpm provided by the function wrapper
        suffix:
            suffix of the bpm pv for bsss monitoring. I.e. TMIT or TMITPID

        output
        --------
        None

        side effects
        -------
        Clears the bsss monitor
        """
        bsss_pv = (
            f"{self.bpms[bpm_idx].pv_name}:{suffix}{self.bpms[bpm_idx].bsa_buff_num}"
        )
        camonitor_clear(bsss_pv)

    @forEveryBpm
    def getBpmBsaData(self, bpm_idx: int, suffix: str) -> None:
        """
        Get the bsa data for the given PV suffix
        e.g. BPMS:SLTD:895:TMIT -> suffix = TMIT
        """
        suffix = suffix.upper()
        suffix_full = f"{suffix}HST"
        suffix_vals = caget(
            f"{self.bpms[bpm_idx].pv_name}:{suffix_full}{self.bpms[bpm_idx].bsa_buff_num}"
        )

        if suffix_vals is None:
            return

        setattr(
            self.bpms[bpm_idx],
            f"{suffix.lower()}_bsa",
            helpers.cagetToList(suffix_vals),
        )

    @forEveryBpm
    def getTpgBsaData(self, bpm_idx: int, suffix: str, tpg_base: str) -> None:
        """
        Get the bsa data for the given PV suffix
        e.g. BPMS:SLTD:895:TMIT -> suffix = TMIT
        """
        suffix = suffix.upper()
        suffix_full = f"{suffix}HST"
        print(f"{tpg_base}:{suffix_full}{self.bpms[bpm_idx].bsa_buff_num}")
        suffix_vals = caget(
            f"{tpg_base}:{suffix_full}{self.bpms[bpm_idx].bsa_buff_num}"
        )

        if suffix_vals is None:
            return

        setattr(
            self.bpms[bpm_idx],
            f"{suffix.lower()}_bsa",
            helpers.cagetToList(suffix_vals),
        )

    @forEveryBpm
    def calcSpacings(self, bpm_idx: int, bpm_att: str):
        """
        calculate the spacings in the given bpm_att
        sets the result to self.bpms[bpm_idx].{bpm_att}_spacings
        see the Bpm class for possible attributes
        """
        bpm_att_val = getattr(self.bpms[bpm_idx], bpm_att)
        if type(bpm_att_val) is not list:
            TypeError("bpm_att must be type list")
        if len(bpm_att_val) is 0:
            return
        setattr(
            self.bpms[bpm_idx], f"{bpm_att}_spacings", helpers.calcSpacings(bpm_att_val)
        )

    @forEveryBpm
    def calcEntryCount(self, bpm_idx: int, bpm_att: str):
        """
        calculate the entry count in the given bpm_att
        sets the result to self.bpms[bpm_idx].{bpm_att}_spacing_count
        see the Bpm class for possible attributes
        """
        bpm_att_spacings = getattr(self.bpms[bpm_idx], f"{bpm_att}_spacings")
        if type(bpm_att_spacings) is not list:
            TypeError("bpm_att_spacings must be type list")
        setattr(
            self.bpms[bpm_idx],
            f"{bpm_att}_spacing_count",
            helpers.calcEntryCount(bpm_att_spacings),
        )

    def processCheck(self, check_nam: str, check_val: bool):
        """
        Keep track of the overall result of the checks
        """
        if check_nam in self.checks:
            if self.checks[check_nam] and check_val:
                return  # all previous bpms have passed, and current bpm has passed
            else:
                self.checks[check_nam] = False
                return  # one or more bpms have failed the given check_name

        self.checks[check_nam] = check_val  # first check of this type

    @forEveryBpm
    def checkTmit(self, bpm_idx: int):
        """
        Make sure the tmit in bsa is above BPM_TMIT_LIMIT if the bpm expects beam
        other wise make sure the tmit in bsa is below BPM_TMIT_LIMIT
        """
        n_expected_tmit = 0
        for tmit in self.bpms[bpm_idx].tmit_bsa:
            if tmit > BPM_TMIT_LIMIT and self.bpms[bpm_idx].tmit_req:
                n_expected_tmit = n_expected_tmit + 1
            if tmit < BPM_TMIT_LIMIT and not self.bpms[bpm_idx].tmit_req:
                n_expected_tmit = n_expected_tmit + 1

        self.bpms[bpm_idx].n_expected_tmit = n_expected_tmit

        if (
            n_expected_tmit == len(self.bpms[bpm_idx].tmit_bsa)
            and len(self.bpms[bpm_idx].tmit_bsa) != 0
        ):  # pass test if all shots have expected tmit and bsa data was taken
            self.processCheck("Expected TMIT", True)
            self.bpms[bpm_idx].has_expected_tmit = True
        else:
            self.processCheck("Expected TMIT", False)
            self.bpms[bpm_idx].has_expected_tmit = False

    @forEveryBpm
    def checkBsssAgainstBsa(self, bpm_idx: int):
        """
        Not well generalized.
        Make sure that each BSSS data is a subset of BSA data
        bsss data point (tmit_bsss[idx] and tmitpid_bsss[idx])
        BSA data point (tmit_bsa[idx] and tmitpid_bsa[idx])
        """

        is_bsss_pid_subset_of_bsa_pid = True
        does_bsss_data_match_bsa = True
        bpm = self.bpms[bpm_idx]
        if (
            bpm.tmitpid_bsss == []
            or bpm.tmit_bsss == []
            or bpm.tmitpid_bsa == []
            or bpm.tmit_bsa == []
        ):
            self.processCheck("BSSS tmitpid is a subset of BSA tmitpid", False)
            self.processCheck("BSSS tmit data is a subset of BSA tmit data", False)
            bpm.all_bsss_pid_in_bsa = bpm.all_bsss_data_in_bsa = False
            return
        for bsss_idx, tmitpid_bsss in enumerate(bpm.tmitpid_bsss):
            if tmitpid_bsss in bpm.tmitpid_bsa:  # all tmitpid in bsss must be in bsa
                bsa_idx = bpm.tmitpid_bsa.index(tmitpid_bsss)
                if (
                    bpm.tmit_bsa[bsa_idx] != bpm.tmit_bsss[bsss_idx]
                ):  # bsss and bsa data point must match
                    does_bsss_data_match_bsa = False
                pass
            else:
                is_bsss_pid_subset_of_bsa_pid = False

        self.processCheck(
            "BSSS tmitpid is a subset of BSA tmitpid", is_bsss_pid_subset_of_bsa_pid
        )
        self.processCheck(
            "BSSS tmit data is a subset of BSA tmit data", does_bsss_data_match_bsa
        )
        bpm.all_bsss_pid_in_bsa = is_bsss_pid_subset_of_bsa_pid
        bpm.all_bsss_data_in_bsa = does_bsss_data_match_bsa

    @forEveryBpm
    def writeInfo(self, bpm_idx):
        """
        Writes info for the bpm in the bpm dict
        """
        bpm = self.bpms[bpm_idx]
        info = []
        info.append(f"---------------")
        info.append(f"bpm: {bpm.pv_name}, buffer: {bpm.bsa_buff_num}")
        info.append(f"bpm TMITPID BSA spacing count: {bpm.tmitpid_bsa_spacing_count}")
        info.append(f"all BSSS pid in BSA: {bpm.all_bsss_pid_in_bsa}")
        info.append(f"all BSSS tmit match BSA tmit on pid: {bpm.all_bsss_data_in_bsa}")
        info.append(f"TMIT above 10e7 required: {bpm.tmit_req}")
        info.append(f"Total pulses: {len(bpm.tmit_bsa)}")
        info.append(f"Pulses with expected TMIT: {bpm.n_expected_tmit}")
        info_str = ""
        for line in info:
            info_str = f"{info_str}\n{line}"
        bpm.info = info_str

    def getInfo(self):
        info = ""
        for bpm in self.bpms:
            info = info + bpm.info + "\n"
        return info

    def getBpmsAsDicts(self):
        bpm_dict = {}
        for bpm_idx, bpm in enumerate(self.bpms):
            bpm_dict[str(bpm_idx)] = vars(bpm)
        return bpm_dict


if __name__ == "__main__":
    buff_nums = {1: 21, 2: 22, 3: 23, 4: 24, 5: 25, 6: 26}
    test_check_bpm = CheckBpm(BPM_CONFIG, buff_nums)
    test_check_bpm.printBpms()
    print(test_check_bpm.bpms[0].bsa_buff_num)
