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


"""

from epics import caget, caget_many
import functools
import numpy as np
import math
from dataclasses import dataclass, field
from config import BSA_BUFF_LOW, BSA_BUFF_HIGH, BPM_CONFIG


@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"""
    pid_bsa: list = field(default_factory=list)
    """pid bsa data associated with the bpm and bsa_buff_num"""
    pid_bsss: list = field(default_factory=list)
    """pid bsss data associated with the bpm and bsa_buff_num"""
    pid_spacings: list = field(default_factory=list)
    """pid spacing between the pid_bsa data"""
    pid_spacing_count: dict[int] = field(default_factory=list)
    """key: pid_spacing, value: count of pid spacing"""
    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, buff_nums: dict):
        """"""
        self._bpms = []
        self.buff_nums = buff_nums
        for dest, dest_bpms in bpm_configs.items():
            for bpm in dest_bpms:
                self.add_bpm(bpm[0], dest, bpm[1], buff_nums[dest])

    @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 for_every_bpm(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            for bpm_idx in range(self.bpmsCount()):
                func(self, bpm_idx, **kwargs)

        return wrapper

    @for_every_bpm
    def print_bpms(self, bpm_idx, **kwargs):
        print(self._bpms[bpm_idx])


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.print_bpms()
    print(test_check_bpm.bpms[0].bsa_buff_num)
