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

import tkinter as tk
from tkinter import ttk
from math import ceil 
import numpy as np
from types import SimpleNamespace
from seqgen_FID import seqgen_FID
from datetime import datetime
import json
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure


def set_limits():
    
    
    G_amp_max = 5                    # mT/m.   Максимальный градиент
    G_slew_max = 45                  # T/m/s.  Максимальная скорость нарастания
    rf_raster_time = 1e-6            # s.      Растр РЧ импульса
    grad_raster_time = 1e-6           # s.      Растр градиентов
    rf_dead_time=0e-6
    adc_dead_time=0e-6
    
    
    
    # Задание общих аппаратных характкристик
    gamma = 42.576e6                   # Hz/T    Гиромагнитное отношение водорода
    G_amp_max = G_amp_max*1e-3*gamma   # Hz/m.   Максимальный градиент
    G_slew_max = G_slew_max*gamma      # Hz/m/s. Максимальная скорость нарастания
    tau_max = G_amp_max/G_slew_max     # s.      Максимальное время нарастания градиента с учетом макс скорости нарастания
    tau_max = np.ceil(tau_max/ grad_raster_time)*grad_raster_time
    

    
    # Чтение заданных в интерфэйс значений 
    BW_per_point = float(M0_dj.textBox1.get())
    N_point = float(M0_dj.textBox2.get())
    TR = float(M0_dj.textBox5.get())*1e-3
    NA = float(M0_dj.textBox6.get())
    freq_offset = float(M0_dj.textBox7.get())
    t_ex = float(M0_dj.textBox8.get())*1e-3
    rf_ringdown_time=float(M0_dj.textBox9.get())*1e-3
    is_sinc_pulse = False
    if M0_dj.radio10.get() == 2:
        is_sinc_pulse = True

    # Длительность кратная растру градиента 10 мкс
    
    t_BW_product_ex = 2.18               # -  Time bandwidth product 
    flip_angle = 90
    apodization = 0.3                    
    BW_ex_pulse = t_BW_product_ex/t_ex   # Hz. BW импульса

    
    BW_full = BW_per_point*N_point
    M0_dj.label4_1.configure(text = str(ceil(BW_full*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.apodization = apodization
    param.t_BW_product_ex = t_BW_product_ex
    param.flip_angle = flip_angle
    param.rf_ringdown_time = rf_ringdown_time
    param.rf_dead_time = rf_dead_time
    param.adc_dead_time = adc_dead_time
    param.freq_offset = freq_offset
    

    param.N_point = N_point   
    param.BW_per_point = BW_per_point
    param.BW_full = BW_full
    param.dG = tau_max
    param.TR = TR
    param.average = NA
    param.is_sinc_pulse = is_sinc_pulse

    output_sequence = seqgen_FID(param)
    output_sequence.plot(win, time_range=(0, np.inf), plot_now=True, tk_plot=True, time_disp="ms")

def save_param():

    output_filename = str(M0_dj.textBox17.get())
    output_sequence = seqgen_FID(param)

    output_sequence.write("seq/"+output_filename)
    
    file = open("seq/"+output_filename + ".json", 'w')
    json.dump(param.__dict__, file, indent = 4)
    file.close()    


def interp_to_scanner():
    file = open("interp/rf_arr.json", 'w')
    json.dump(param.__dict__, file, indent=4)
    file.close()
    print("interp")

### Default values ###
  
BW_per_point = 100
N_point = 512     
TR = 200 
NA = 1
freq_offset = 0
t_ex = 1
rf_ringdown_time = 100e-3

win = tk.Tk()
win.title('FID')
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="FID")

M0_dj = SimpleNamespace()

 

# Slice thickness, m  
tk.Label(Main, text = 'BW_per_point, Hz').grid(row=1, column=0,sticky = "E")
M0_dj.textBox1 = tk.Entry(Main, width = 6)
M0_dj.textBox1.insert(0, BW_per_point)
M0_dj.textBox1.grid(row=1, column=1)
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.textBox2 = tk.Entry(Main, width = 6)
M0_dj.textBox2.insert(0, N_point)
M0_dj.textBox2.grid(row=2, column=1)
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 = 'TR, ms')
M0_dj.label5.grid(row=4, column=0,sticky = "E")
M0_dj.textBox5 = tk.Entry(Main, width = 6)
M0_dj.textBox5.insert(0, TR)
M0_dj.textBox5.grid(row=4, column=1)
M0_dj.label5_1 = tk.Label(Main)
M0_dj.label5_1.grid(row=4, column=2)

M0_dj.label6 = tk.Label(Main, text = 'NA')
M0_dj.label6.grid(row=5, column=0,sticky = "E")
M0_dj.textBox6 = tk.Entry(Main, width = 6)
M0_dj.textBox6.insert(0, NA)
M0_dj.textBox6.grid(row=5, column=1)
M0_dj.label6_1 = tk.Label(Main)
M0_dj.label6_1.grid(row=5, column=2)

M0_dj.label7 = tk.Label(Main, text = 'Freq_offset')
M0_dj.label7.grid(row=6, column=0,sticky = "E")
M0_dj.textBox7 = tk.Entry(Main, width = 6)
M0_dj.textBox7.insert(0, freq_offset)
M0_dj.textBox7.grid(row=6, column=1)


M0_dj.label8 = tk.Label(Main, text = 'RF_pulse_dur, ms')
M0_dj.label8.grid(row=7, column=0,sticky = "E")
M0_dj.textBox8 = tk.Entry(Main, width = 6)
M0_dj.textBox8.insert(0, t_ex)
M0_dj.textBox8.grid(row=7, column=1)


M0_dj.label9 = tk.Label(Main, text = 'RF-ADC delay, ms')
M0_dj.label9.grid(row=8, column=0,sticky = "E")
M0_dj.textBox9 = tk.Entry(Main, width = 6)
M0_dj.textBox9.insert(0, rf_ringdown_time)
M0_dj.textBox9.grid(row=8, column=1)


M0_dj.radio10 = tk.IntVar() 
M0_dj.radio10.set(1)

M0_dj.label10 = tk.Label(Main, text = "Pulse_type:")
M0_dj.label10.grid(row=9, column=0, sticky = "E")
M0_dj.R1_10 = tk.Radiobutton(Main, text="block", variable=M0_dj.radio10, value=1) 
M0_dj.R1_10.grid(row=9, column=1 ) 
M0_dj.R2_10 = tk.Radiobutton(Main, text="sinc", variable=M0_dj.radio10, value=2) 
M0_dj.R2_10.grid(row=9, 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=3, column=5,sticky = "W")

M0_dj.btn1 = tk.Button(Main, text = 'Load to scanner', command = interp_to_scanner, width = 20)
M0_dj.btn1.grid(row=5, 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, "FID_" + datetime.now().strftime("%d%m%y_%H%M"))
M0_dj.textBox17.grid(row=7, column=5, columnspan=3,sticky = "W")



win.mainloop()



