from cristallina import pgroup,cta,detectors,camera_channels,bs_channels,pvs,logger
import subprocess
from time import sleep
from slic.utils import PV

########################## Measurements scripts for the DilSc runs with meander devices

CTA_sequence_start_PID = PV("SAR-CCTA-ESC:seq0Ctrl-StartedAt-O")

def get_last_run_number():
    with open(f'/sf/cristallina/data/{pgroup}/raw/run_info/LAST_RUN') as f:
        lines = f.readlines()
    return int(lines[0])

def dil_run(run_comment=None, duration=70, seconds_before=5, seconds_after=0, Hz100=False,test=False):
    last_rn = get_last_run_number()
    
    # Start ZH_DAQ
    subprocess.Popen(['/sf/cristallina/applications/devices/zhinst/record.sh', f'{last_rn+1}', f'{duration + seconds_before + seconds_after}'])
    sleep(6) # approximate startup time to start the ZHinstruments lockin acquisition

    sleep(seconds_before)

    # Start the CTA sequence
    cta.cta_client.start()

    # Open shutter
    if Hz100:
        shutter.open()

    # Wait until done
    sleep(duration)

    # Close shutter
    if Hz100:
        shutter.close()

    # Ask for the first pid in the sequence
    CTA_start_PID = int(CTA_sequence_start_PID.get())
    
    # Calculate PIDs that we want to download
    start_PID = CTA_start_PID - seconds_before*100
    end_PID   = CTA_start_PID + duration*100

    # Data retrieval does not allow empty list, so creating a new variable 
    if detectors == [] or detectors == None:
        used_detectors = {}
    else:
        used_detectors = {"JF16T03V01":{}}

    # Wait time added so that the data arrives in the databuffer. If sf_daq_client asks too soon, usually PV data does not get saved.
    sleep(15)
    
    if test is not True:
        # TODO: change to SFAcquisition.retrieve(...) from slic
        # Ask the DAQ client to download the data
        run_number = sf_daq_client.retrieve_data_from_buffer(pgroup=pgroup, user_tag=run_comment,
                                camera_channels=camera_channels, bsread_channels=bs_channels, epics_channels=pvs,
                                detectors=used_detectors,
                                start_pulseid=start_PID, stop_pulseid=end_PID,
                                rate_multiplicator=1,
                                )
    print('\n')
    # print(f' Sequence done.\n Run {run_number} created. \n First PID in the CTA sequence: {start_PID}\n')
    logger.info(f' Sequence done.\n Run {run_number} created. \n First PID in the CTA sequence: {start_PID}\n')