# -*- coding: utf-8 -*-

# import LF_scanner.pypulseq as pp
import numpy as np
import pypulseq as pp


def seqgen_FID(param):
    # Read scanner parameters from the params structure
    scanner_parameters = pp.Opts(max_grad=param.G_amp_max, grad_unit='Hz/m', \
                                 max_slew=param.G_slew_max, slew_unit='Hz/m/s', \
                                 grad_raster_time=param.grad_raster_time, \
                                 rf_raster_time=param.rf_raster_time, \
                                 adc_raster_time=1 / (param.BW_per_point * param.N_point), \
                                 block_duration_raster=max(param.grad_raster_time, param.rf_raster_time), \
                                 rf_dead_time=param.rf_dead_time, \
                                 rf_ringdown_time=param.rf_ringdown_time, \
                                 adc_dead_time=param.adc_dead_time)

    # Generate the RF pulse
    exc_pulse_offsets = 0

    if param.is_sinc_pulse:
        exc_pulse = pp.make_sinc_pulse(flip_angle=param.flip_angle / 180 * np.pi, \
                                       duration=np.double(param.t_ex), \
                                       apodization=param.apodization, \
                                       freq_offset=param.freq_offset, \
                                       phase_offset=0, \
                                       time_bw_product=param.t_BW_product_ex, \
                                       system=scanner_parameters)
    else:
        exc_pulse = pp.make_block_pulse(flip_angle=param.flip_angle / 180 * np.pi, system=scanner_parameters,
                                        duration=np.double(param.t_ex))

    # Generate the ADC event
    adc_module = pp.make_adc(num_samples=param.N_point, duration=1 / param.BW_per_point, system=scanner_parameters)
    adc_module.phase_offset = 0

    # Calculate the TR fillers
    TR = param.TR
    tr_delay = TR - pp.calc_duration(exc_pulse) - pp.calc_duration(adc_module)
    tr_delay = np.ceil(tr_delay / param.grad_raster_time) * param.grad_raster_time
    tr_delay = pp.make_delay(tr_delay)

    seq = pp.Sequence(system=scanner_parameters)

    for n in range(int(param.average)-1):
        # Add RF and gradient block
        seq.add_block(exc_pulse)
        seq.add_block(adc_module)
        seq.add_block(tr_delay)
    seq.add_block(exc_pulse)
    seq.add_block(adc_module)

    print(pp.check_timing.check_timing(seq))
    return seq
