from epics import caput, caget, PV
from time import sleep
from pandas import DataFrame, Series
from scipy.optimize import curve_fit
from datetime import datetime
from numpy import linspace, array, append
from PyQt5.QtCore import QRunnable, pyqtSignal, QObject
import os


class TestSignal(QObject):
    signal = pyqtSignal(dict)

class RunLVDT(QRunnable):
    def __init__(self, args) -> None:
        super().__init__()
        self.args = args
        self.signal = TestSignal()

    def run(self) -> None:
        CalibrateLVDT(self.args.device, self.args.step, self.args.sub, self.args.measurements, self.args.poly, self.args.dir, self.signal.signal)
        
def CalibrateLVDT(device: str, step: float, sub: int, measurements: int, poly: int, dir: int, link: pyqtSignal=None) -> None:
    """
    1. Move both jaws to their outer limit and set software limit past limit switch
        - For NEGY this should be -52mm (Low Limit Switch)
        - For POSY this should be +52mm (High Limit Switch)
        - If no axis, start at high limit
    2. Example command line
        - python Calibrate.py --type lvdt --device COLL:BPN26:424:POSY --step 5 --sub 1 --measurements 4 --poly 7
    """
    
    # Data
    sigs = {'lvdt_forward': array([], dtype=float), 'lvdt_reverse': array([], dtype=float),
            'lvdt_polyfit': array([], dtype=float), 'motor_forward': array([], dtype=float),
            'motor_reverse': array([], dtype=float), 'motor_polyfit': array([], dtype=float),
            'coeff_old': array([], dtype=float), 'coeff_new': array([], dtype=float),
            'save_name': 'bad_exit.png', 'complete': False}

    # Path Reconciliation
    now = datetime.now()
    now_fmt = now.strftime('%b-%d-%Y-%I-%M%p')
    cal_path = os.environ.get('PHYSICS_DATA') + '/genMotion/lvdt/' + device.replace(':','_')
    if not os.path.isdir(cal_path): os.makedirs(cal_path)
    data_file_name =  f'{cal_path}/DATA_{now_fmt}.csv'
    sigs['save_name'] = f'{cal_path}/PLOT_{now_fmt}.png'

    # Device Naming Convention
    multiplier = 1000 if 'WIRE' in device else 1
    coeff_prefix = 'LVPOS_SUB' if sub==1 else 'LVPOS'
    convention = ['HLS', 'TWF', 'LLS', 'TWR']
    if dir != 0: convention = convention[2:] + convention[:2]
    
    # Get Previous Params
    curr_twv = float(caget(f'{device}:MOTR.TWV'))
    sigs['coeff_old'] = array([float(caget(f"{device}:{coeff_prefix}.{chr(ord('A') + i)}")) for i in range(8)], dtype=float)

    # Set Tweek Value and Move Limits
    caput(f'{device}:MOTR.LLM', -200*multiplier)
    caput(f'{device}:MOTR.HLM', 200*multiplier)
    caput(f'{device}:MOTR.TWV', step*multiplier)

    # Sweep
    for j in range(2):
        movdir = 'forward' if j==1 else 'reverse'
        
        while True:
            if bool(caget(f'{device}:MOTR.{convention[0 + 2*j]}')):
                break
            sleep(2)
            for i in range(measurements):
                sleep(1)
                motor_pos = float(caget(f'{device}:MOTR.RBV'))
                lvdt_pos = float(caget(f'{device}:LVRAW'))
                if link is not None:
                    sigs[f'lvdt_{movdir}'] = append(sigs[f'lvdt_{movdir}'], lvdt_pos)
                    sigs[f'motor_{movdir}'] = append(sigs[f'motor_{movdir}'], motor_pos)
                    link.emit(sigs)
            caput(f'{device}:MOTR.{convention[1 + 2*j]}', 1, wait=True, timeout=10)
            
    # Fit
    polyfunc = lambda x, *coeffs: sum(c * x**i for i, c in enumerate(coeffs))
    lvdt_pos = append(sigs['lvdt_forward'], sigs['lvdt_reverse'])
    moto_pos = append(sigs['motor_forward'], sigs['motor_reverse'])
    popt, _ = curve_fit(polyfunc, lvdt_pos, moto_pos, p0=[0]*(poly+1))
    sigs['coeff_new'] = array(popt, dtype=float)
    sigs['lvdt_polyfit'] = linspace(min(lvdt_pos), max(lvdt_pos), len(lvdt_pos))
    sigs['motor_polyfit'] = array([polyfunc(i, *popt) for i in sigs['lvdt_polyfit']], dtype=float)
    sigs['complete'] =True
    link.emit(sigs)

    # Save Data
    tosave = DataFrame({k:Series(v) for k,v in sigs.items()}, index=None)
    tosave.columns = [idx.upper() for idx in tosave.columns]
    tosave.to_csv(data_file_name,float_format='%+.5E', index=None, na_rep='            ')
    
    # Reset Values
    caput(f'{device}:MOTR.TWV', curr_twv)
    caput(f'{device}:MOTR.LLM', min(moto_pos))
    caput(f'{device}:MOTR.HLM', max(moto_pos))
