# -*- coding: utf-8 -*-
"""
A subroutine to add SPAIR fat suppression block.
Requires the params structure as input.

Need to think of the reequired output (pulse sequence variable itself?)

@author: petrm
"""

#imports
from math import pi
import numpy as np

from MRI_sequences.pypulseq.make_delay import make_delay
from MRI_sequences.pypulseq.make_gauss_pulse import make_gauss_pulse
from MRI_sequences.pypulseq.make_trapezoid import make_trapezoid
from MRI_sequences.pypulseq.calc_duration import calc_duration

def SPAIR_block(params, scanner_parameters, gz90):
    #function creates CHESS saturation block with accompanied gx and gy spoiled gradients
    params['B0'] = 1.5  # TODO add to GUI
    params['FS_sat_ppm'] = -3.30  # TODO add to GUI
    params['FS_pulse_duration'] = 0.01  # TODO add to GUI
    #params['IR_time'] = 0.140  # SPAIR # TODO add to GUI
    params['BW_sat'] = -176.26464
    g_rf_area = gz90.area * 10

    FS_sat_frequency = params['B0'] * 1e-6 * params['FS_sat_ppm'] * params['gamma']
    flip_SPAIR = round(180 * pi / 180)

    rf_SPAIR = make_gauss_pulse(flip_angle=flip_SPAIR, system=scanner_parameters, duration=params['FS_pulse_duration'],
                             bandwidth=abs(params['BW_sat']), freq_offset=FS_sat_frequency)
    gx_SPAIR = make_trapezoid(channel="x", system=scanner_parameters, delay=calc_duration(rf_SPAIR),
                           area= g_rf_area, rise_time=params['dG'])
    gy_SPAIR = make_trapezoid(channel="y", system=scanner_parameters, delay=calc_duration(rf_SPAIR),
                           area= g_rf_area, rise_time=params['dG'])

    delay_IR = np.ceil(params['TI'] / scanner_parameters.grad_raster_time) * scanner_parameters.grad_raster_time
    delay_IR = make_delay(delay_IR)

    return rf_SPAIR, gx_SPAIR, gy_SPAIR, delay_IR

