import sys
import os
from stat import S_IREAD, S_IRGRP, S_IROTH
import cothread
import cothread.catools as ca
import time
import datetime
import numpy as np
from collections import namedtuple
import logging
_log = logging.getLogger(__name__)

os.environ['EPICS_CA_MAX_ARRAY_BYTES'] = '10000000'

GOOD = 0
WARN = 1
ERR = 2

# Indices for optional info PVs
STAT = 0
CNT = 1
ERRCNT = 2
TSERRCNT = 3
MSG = 4
TS = 5
DIR1 = 6
DIR2 = 7

# PVinfo
# name = PV name
# prec = Significant digits to print to file
# tsmatch = PV timestamp should match other fault data
PVinfo = namedtuple("PVinfo", "name prec tsmatch")


class CreatePVinfo(object):
    def __init__(self, name, prec=0, tsmatch=0):
        self.name = name
        self.prec = prec
        self.tsmatch = tsmatch
        _log.debug("Create PVInfo with name %s prec %i tsmatch %i" %
                   (name, prec, tsmatch))
        self.create()

    def create(self):
        return PVinfo(self.name, self.prec, self.tsmatch)


# Stolen from FEED launcher
# helper to ignore current value of
# subscription which is the first
# update sent after (re)connect
class Delta(object):
    def __init__(self, action):
        self.connected, self.action = False, action

    def __call__(self, val):
        if not val.ok:
            _log.debug("%s disconnect" % val.name)
            self.connected = False
        elif self.connected:
            _log.debug("%s update %s" % (val.name, val))
            self.action(val)
        else:
            _log.debug("%s (re-)connect %s" % (val.name, val))
            self.connected = True


class FaultMonitor(object):
    def __init__(self, pvpref, dirname, filepref):

        self.pvpref = pvpref

        _log.debug("rf_fault_save %s - Entered FaultMonitor" % pvpref)

        self.dirname = dirname
        self.filepref = filepref

        self.pvs = []

        # First entry must be the fault timestamp record
        # Its timestamp is the reference to which others are compared
        self.pvs.append(CreatePVinfo("%sACQ_FLT_TS" % self.pvpref, tsmatch=1))

        # Fault PV triggers waveform save
        self.faultpv = "%sRFS:FLTINTLK_FIRST" % self.pvpref

        self.add_scalars()
        self.add_wfs()

        self.faultvals = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20]
        self.faultstrs = ["PLL", "IOC", "RESSUM", "RESLINK", "SSA", "QUENCH"]

        if len(self.faultvals) != len(self.faultstrs):
            raise Exception("rf_fault_save %s fault value %i and string %i "
                            "lengths do not match" %
                            (self.pvpref, len(self.faultvals),
                             len(self.faultstrs)))

        # Extract just PV names for use in caget
        self.pvnames = []
        _log.info("rf_fault_save %s - Will save these PVs' values when "
                  "interlock faults:" % self.pvpref)
        for pv in self.pvs:
            name = pv.name
            _log.debug("    %s" % name)
            self.pvnames.append(name)

        try:
            ca.caget(self.pvnames)
        except Exception as e:
            _log.exception("rf_fault_save %s error during caget" % self.pvpref)
            raise e

        self.pstat_init()

        # Set formatting to imitate caget output
        np.set_printoptions(threshold=sys.maxsize)
        np.set_printoptions(linewidth=sys.maxsize)

        self.evt = cothread.EventQueue()

        self.cmd_start = ca.camonitor(b'%s' % self.faultpv,
                                      Delta(lambda _val:
                                            self.evt.Signal("START")),
                                      notify_disconnect=True)
        try:
            while True:
                _log.info("rf_fault_save %s - Waiting for fault" % self.pvpref)

                self.evt.Wait()

                fault = ca.caget('%s' % (self.faultpv))

                if fault != 0:
                    self.handle_start(fault)
                else:
                    _log.debug("rf_fault_save %s - Non-fault value, skipping" %
                               self.pvpref)
        except Exception as e:
            _log.exception("rf_fault_save %s - error in "
                           "waiting/handling event" % self.pvpref)
            raise e

    # Optional recording of program status/stats - if supporting PVs exist
    def pstat_init(self):
        # This PV order assumed
        self.pstatpvs = []
        self.pstatpvs.append("%sFLTDATA_STAT" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_SAVECNT" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_ERRCNT" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_TSERRCNT" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_MSG" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_TSLAST" % self.pvpref)
        # Use log directory PVs to host data file location
        self.pstatpvs.append("%sFLTDATA_LOGDIR1" % self.pvpref)
        self.pstatpvs.append("%sFLTDATA_LOGDIR2" % self.pvpref)
        try:
            ca.caget(self.pstatpvs)
            self.pstat = 1  # Record program status
            ca.caput(self.pstatpvs[DIR1], self.dirname[0:37])
            ca.caput(self.pstatpvs[DIR2], self.dirname[37:77])
        except Exception as e:
            _log.warning(e)
            _log.warning("rf_fault_save %s - "
                         "Error reading program status PVs, "
                         "will not record status/counts" %
                         self.pvpref)
            self.pstat = 0  # Do not record program status

    # Update optional status/stats PVs
    def pstat_update(self, success, tsmatch, tstr):
        try:
            pstat_init = ca.caget(self.pstatpvs)
            if success is True:
                stat = GOOD
                ca.caput(self.pstatpvs[CNT], pstat_init[CNT] + 1)
                msg = "Saved"
            else:
                stat = ERR
                ca.caput(self.pstatpvs[ERRCNT], pstat_init[ERRCNT] + 1)
                msg = "Save failed"
            if tsmatch is False:
                if stat == GOOD:  # Demote status
                    stat = WARN
                ca.caput(self.pstatpvs[TSERRCNT], pstat_init[TSERRCNT] + 1)
                msg = "%s - timestamp mismatch" % msg
            ca.caput(self.pstatpvs[MSG], msg)  # 39 character limit
            ca.caput(self.pstatpvs[STAT], stat)
            ca.caput(self.pstatpvs[TS], tstr)
        except Exception as e:
            _log.warning(e)
            _log.warning("rf_fault_save %s - Unable to update "
                         "program status PVs" %
                         self.pvpref)

    # Fault waveforms
    def add_wfs(self):
        # Define LCLS fault waveforms to acquire
        sig = ["CAV", "FWD", "REV"]
        attr = ["A", "P", "PWR", "I", "Q", "T"]
        prec = [7, 8, 7, 7, 7, 7]
        # All WF timestamps should match except time base;
        # it only updates on change
        tsmatch = [1, 1, 1, 1, 1, 0]

        for s in sig:
            for (a, p, t) in zip(attr, prec, tsmatch):
                self.pvs.append(CreatePVinfo("%s%s:FLT%sWF" %
                                (self.pvpref, s, a), prec=p, tsmatch=t))

    # Additional PVs to acquire
    def add_scalars(self):
        self.pvs.append(CreatePVinfo(self.faultpv, 0, 0))
        self.pvs.append(CreatePVinfo("%sACQ_FLT_DELAY" % self.pvpref, prec=3))
        self.pvs.append(CreatePVinfo("%sACQ_FLT_DELAY_TICKS" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sACQ_DECIM" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sMAGN_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sREAL_MIN_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sREAL_MAX_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sREACTIVE_MIN_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sREACTIVE_MAX_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sAMPFB_GAIN_P_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sAMPFB_GAIN_I_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sPHAFB_GAIN_P_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sPHAFB_GAIN_I_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%s8PI9_FDELTA" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sLOWPASS_BW" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSEL_POFF_RBV" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sADES" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sQLOADED" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sFWD:SCALE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sREV:SCALE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sCAV:SCALE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sRFMODE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sRFSTATE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sBCOEFM" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sBCOEFP" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sPROBECALTS" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sPROBECALSTS" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sCAV:CALSUM" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sCAV:CALSTAT" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSSA:DRV_MAX" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSSA:REACTIVE" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSSA:CALSTS" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSSA:CALTS" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sSSA:CALSTAT" % self.pvpref))
        self.pvs.append(CreatePVinfo("%sQUENCH_THRESH" % self.pvpref, prec=1))
        self.pvs.append(CreatePVinfo("%sACQ_SAMP_PERIOD" % self.pvpref, prec=8))

    def handle_start(self, fault):

        pstat_success = False  # Initialize to failure

        vals = ca.caget(self.pvnames, format=ca.FORMAT_TIME)

        _log.debug("rf_fault_save %s - New fault. Processing..." %
                   self.pvpref)

        # Check for timestamp match
        # If mismatch, still save all data, with warning
        tsmatch = True
        (sec, nsec) = vals[0].raw_stamp
        # Only check records whose timestamps should match
        for index, val in enumerate(vals):
            if self.pvs[index].tsmatch:
                _log.debug("check timestamp for %s" % self.pvs[index].name)
                (s, ns) = val.raw_stamp
                if (s != sec) or (ns != nsec):
                    tsmatch = False

        # Use timestamp record (first in list) as 'master' time,
        # used in file names, etc., in case of mismatch with other records
        tstr = time.strftime("%Y%m%d_%H%M%S", time.localtime(sec))
        # tstr2 friendler format, used in timestamp PV
        tstr2 = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(sec))

        # Build string of faults based on fault PV value
        # There should only be one, but just in case...
        fstr = ""
        for (f, s) in zip(self.faultvals, self.faultstrs):
            if fault & f:
                fstr = "%s_%s" % (fstr, s)

        filename = "%s_%s%s" % (self.filepref, tstr, fstr)
        if tsmatch is False:
            filename = "%s-TimestampError" % filename

        dirname = "%s/%s" % (self.dirname, filename)

        fullfilename = "%s/%s.txt" % (dirname, filename)

        fp = None

        try:
            # Use current time for informational message
            _log.info("rf_fault_save %s - Save fault data to %s" %
                      (self.pvpref, fullfilename))
            os.mkdir(dirname)
            fp = open(fullfilename, 'w')
            if fp is not None:
                fp.write('# %s %s Interlock Fault %s\n'
                         % (self.pvpref, fstr, tstr))
                for index, val in enumerate(vals):
                    if val.element_count > 1:
                        # Set significant digits
                        formatstr = "{:.%sg}" % self.pvs[index].prec
                        my_formatter = formatstr.format
                        np.set_printoptions(formatter={'float_kind':
                                            my_formatter})
                        tmp = np.array2string(val)
                        # Strip brackets to imitate caget output
                        tmp = str(tmp).replace('[', '').replace(']', '')
                    else:
                        tmp = val
                    fp.write('%s %s %s\n' % (val.name,
                             datetime.datetime.fromtimestamp(val.timestamp).
                             strftime("%Y-%m-%d_%H:%M:%S.%f"), tmp))
                pstat_success = True
            else:
                _log.error("rf_fault_save %s - Failed to open file" %
                           self.pvpref)
                pstat_success = False
        except Exception as e:
            _log.error(e)
            _log.error("rf_fault_save %s - File write failed" % self.pvpref)
            pstat_success = False

        finally:
            if fp is not None:
                # Set read-only
                os.chmod(fullfilename, S_IREAD | S_IRGRP | S_IROTH)
                fp.close()
            if self.pstat:
                self.pstat_update(pstat_success, tsmatch, tstr2)


def usage():
    print('Script loops forever, monitoring fault status.')
    print('When a fault occurs, save waveform and other data to file')
    print('python rf_fault_save_lcls.py -p <pvpref> -d <dirname> -f '
          '<filepref>')
    print('Example:')
    print('python rf_fault_save_lcls.py -p ACCL:L1B:0210: -d '
          '$PHYSICS_DATA/rf_lcls2/fault_data/ACCL_L1B_0210 -f ACCL_L1B_0210')


if __name__ == '__main__':

    from argparse import ArgumentParser
    parser = ArgumentParser(description='RF fault waveform save')

    parser.add_argument('-p', '--pvpref', dest='pvpref',
                        help='Fault PVs prefix, often cavity name with'
                             'terminating colon', required=True)
    parser.add_argument('-d', '--dirname', dest='dirname',
                        help='Full path to output data directory. Must '
                        'exist. Script will create subdirectories here',
                        required=True)
    parser.add_argument('-f', '--filepref', dest='filepref',
                        help='Output data file prefix, used in new '
                        'subdirectories and file names', required=True)

    args = parser.parse_args()

    if not os.path.isdir(args.dirname):
        raise Exception('rf_fault_save_lcls: data directory %s'
                        ' does not exist' % args.dirname)

    logname = "%s/rf_fault_save.log" % args.dirname
    logging.basicConfig(filename=logname, filemode='w', level=logging.DEBUG,
                        format='%(asctime)s - %(levelname)s - %(message)s')

    FaultMonitor(args.pvpref, args.dirname, args.filepref)
