# -*- coding: utf-8 -*-
"""
Created on Mon Jul  3 17:53:21 2023

@author: zilya
"""


import tkinter as tk
from tkinter import ttk
from math import ceil 
import numpy as np
from types import SimpleNamespace
from seqgen_STEAM import seqgen_STEAM
from datetime import datetime
import json


def set_limits():
    
    # Задание общих аппаратных характкристик
    gamma = 42.576e6                   # Hz/T    Гиромагнитное отношение водорода
    G_amp_max = 37.8                    # mT/m.   Максимальный градиент
    G_amp_max = G_amp_max*1e-3*gamma   # Hz/m.   Максимальный градиент
    G_slew_max = 121                   # T/m/s.  Максимальная скорость нарастания
    G_slew_max = G_slew_max*gamma      # Hz/m/s. Максимальная скорость нарастания
    rf_raster_time = 5e-7             # s.      Растр РЧ импульса
    grad_raster_time = 10e-6           # s.      Растр градиентов
    tau_max = G_amp_max/G_slew_max     # s.      Максимальное время нарастания градиента с учетом макс скорости нарастания
    tau_max = np.ceil(tau_max/ grad_raster_time)*grad_raster_time
    
        # --- Параметры РЧ импульса -----
    rf_ringdown_time=20e-6
    rf_dead_time=100e-6
    adc_dead_time=10e-6
 
    
    # Чтение заданных в интерфэйс значений 
    average = float(M0_dj.textBox9.get())
    voxel_thkn = 10e-3
    BW_per_point = 2
    N_point = 512
    tau1 = 5.8e-3
    tau2 = 3.4e-3
    

    t_ex = 5.510e-3                      # s. Длительность возбуждающего импульса
    t_BW_product_ex = 2.18               # -  Time bandwidth product 
    flip_angle = 90
    apodization = 0.3                    # s. Длительность возбуждающего импульса
    BW_ex_pulse = t_BW_product_ex/t_ex   # Hz. BW импульса
    TR = 3
    
    voxel_thkn = 10e-3
    BW_per_point = 2
    N_point = 512
    BW_full = BW_per_point*N_point
    t_read = 1/BW_per_point
    
    M0_dj.label1_1.configure(text = BW_per_point)
    M0_dj.label2_1.configure(text = N_point)
    M0_dj.label4_1.configure(text = BW_full)
    M0_dj.label5_1.configure(text = str(ceil(voxel_thkn*1000)/1000))
    M0_dj.label6_1.configure(text = str(ceil(tau1*10000)/10000))
    M0_dj.label7_1.configure(text = str(ceil(tau2*10000)/10000))
    M0_dj.label8_1.configure(text = str(ceil(TR*1000)/1000))

    
    global param
    param = SimpleNamespace()
    param.G_amp_max = G_amp_max
    param.G_slew_max = G_slew_max
    param.gamma = gamma
    param.grad_raster_time = grad_raster_time
    param.rf_raster_time = rf_raster_time
    
    param.t_ex = t_ex                      
    param.t_BW_product_ex = t_BW_product_ex         
    param.FA = flip_angle
    param.apodization = apodization                    
    param.BW_ex_pulse = BW_ex_pulse   
    param.rf_ringdown_time = rf_ringdown_time
    param.rf_dead_time = rf_dead_time
    param.adc_dead_time = adc_dead_time
   
    

    param.voxel_thkn = voxel_thkn 

    param.N_point = N_point   
    param.BW_per_point = BW_per_point
    param.dG = tau_max
    param.tau1 = tau1
    param.tau2 = tau2
    param.TR = TR
    param.average = average


def save_param():

    output_filename = str(M0_dj.textBox17.get())
    output_sequence = seqgen_STEAM(param)
    output_sequence.plot(time_range = (0.000, 0.03))
    output_sequence.write(output_filename)
    
    file = open(output_filename + ".json", 'w')
    json.dump(param.__dict__, file, indent = 4)
    file.close()    


### Defoult values ###
       
average = 1 

win = tk.Tk()
win.title('STEAM')
win.geometry("520x420+100+100")
win.resizable(False,False)

# создаем набор вкладок
notebook = ttk.Notebook()
notebook.pack(expand=True, fill='both')

Main = tk.Frame(notebook)
Main.pack(fill='both', expand=True)
notebook.add(Main, text="Main")

M0_dj = SimpleNamespace()


tk.Label(Main, text = 'BW_per_point, Hz').grid(row=1, column=0,sticky = "E")
M0_dj.label1_1 = tk.Label(Main)
M0_dj.label1_1.grid(row=1, column=2)
 
tk.Label(Main, text = 'N_point').grid(row=2, column=0,sticky = "E")
M0_dj.label2_1 = tk.Label(Main)
M0_dj.label2_1.grid(row=2, column=2)

 
M0_dj.label4 = tk.Label(Main, text = 'BW_full, Hz')
M0_dj.label4.grid(row=3, column=0,sticky = "E")
M0_dj.label4_1 = tk.Label(Main)
M0_dj.label4_1.grid(row=3, column=2)


M0_dj.label5 = tk.Label(Main, text = 'sl_thkn, m')
M0_dj.label5.grid(row=4, column=0,sticky = "E")
M0_dj.label5_1 = tk.Label(Main)
M0_dj.label5_1.grid(row=4, column=2)

M0_dj.label6 = tk.Label(Main, text = 'tau1')
M0_dj.label6.grid(row=5, column=0,sticky = "E")
M0_dj.label6_1 = tk.Label(Main)
M0_dj.label6_1.grid(row=5, column=2)


M0_dj.label7 = tk.Label(Main, text = 'tau2')
M0_dj.label7.grid(row=6, column=0,sticky = "E")
M0_dj.label7_1 = tk.Label(Main)
M0_dj.label7_1.grid(row=6, column=2)

M0_dj.label8 = tk.Label(Main, text = 'TR')
M0_dj.label8.grid(row=7, column=0,sticky = "E")
M0_dj.label8_1 = tk.Label(Main)
M0_dj.label8_1.grid(row=7, column=2)

tk.Label(Main, text = 'Averages').grid(row=8, column=0,sticky = "E")
M0_dj.textBox9 = tk.Entry(Main, width = 6)
M0_dj.textBox9.insert(0, average)
M0_dj.textBox9.grid(row=8, column=1)
M0_dj.label9_1 = tk.Label(Main)
M0_dj.label9_1.grid(row=8, column=2)



set_limits()

M0_dj.btn1 = tk.Button(Main, text = 'Set', command = set_limits, width = 10)
M0_dj.btn1.grid(row=1, column=5,sticky = "W")



M0_dj.btn1 = tk.Button(Main, text = 'Save', command = save_param, width = 10)
M0_dj.btn1.grid(row=4, column=5,sticky = "W")

# filename
M0_dj.label17= tk.Label(Main, text = 'Output file name',width = 13)
M0_dj.label17.grid(row=6, column=5,sticky = "W")
M0_dj.textBox17 = tk.Entry(Main,width = 25)
M0_dj.textBox17.insert(0, "STEAM_" + datetime.now().strftime("%d%m%y_%H%M"))
M0_dj.textBox17.grid(row=7, column=5, columnspan=3,sticky = "W")



win.mainloop()


